![](/img/trans.png)
[英]How to remove the last character from all lines but only if it is a certain character
[英]How to remove only the last word from a file
我创建了以下Perl单行代码,以便从文件中删除单词
该Perl还转义了@
, $
或*
等特殊字符,因此每个包含特殊字符的单词都将从文件中删除。
如何更改Perl语法以仅删除文件中的最后一个匹配单词而不删除所有单词?
例
more file
Kuku
Toto
Kuku
kuku
export REPLACE_NAME="Kuku"
export REPLACE_WITH=""
perl -i -pe 'next if /^#/; s/(^|\s)\Q$ENV{REPLACE_NAME }\E(\s|$)/$1$ENV{ REPLACE_WITH }$2/' file
预期成绩
more file
Kuku
Toto
Kuku
另一个例子
什么时候- 导出REPLACE_NAME =“ mark @ $!”
more file
mark@$!
hgst#@
hhfdd@@
预期成绩
hgst#@
hhfdd@@
使用Tie :: File使其更容易。
$ perl -MTie::File -E'tie @file, "Tie::File", shift or die $!; $file[-1] =~ s/\b\Q$ENV{REPLACE_NAME}\E\b/$ENV{REPLACE_WITH}/' file
更新:重新编写程序以对其进行说明。
# Load the Tie::File module
use Tie::File;
# Tie::File allows you to create a link between an array and a file,
# so that any changes you make to the array are reflected in file.
# The "tie()" function connects the file (passed as an argument and
# therefore accessible using shift()) to a new array (called @file).
tie my @file, 'Tie::File', shift
or die $!;
# The last line of the file will be in $file[-1].
# We use s/.../.../ to make a substitution on that line.
$file[-1] =~ s/\b\Q$ENV{REPLACE_NAME}\E\b/$ENV{REPLACE_WITH}/;
更新:现在您已经更改了需求规格。 您要删除字符串的最后一次出现,而不必出现在文件的最后一行。
老实说,我认为您已经超越了我在命令行开关中编写的那种任务。 它会编写一个单独的程序,看起来像这样:
#!/usr/bin/perl
use strict;
use warnings;
use Tie::File;
tie my @file, 'Tie::File', shift
or die $!;
foreach (reverse @file) {
if (s/\b\Q$ENV{REPLACE_NAME}\E\b/$ENV{REPLACE_WITH}/) {
last;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.