如何只删除文件中的最后一个单词

时间:2016-07-07 13:30:50

标签: linux bash perl

我创建了以下Perl单行程序,以便从文件中删除单词

此Perl还会转义$* more file Kuku Toto Kuku kuku 等特殊字符,因此每个包含特殊字符的单词都会从文件中删除。

如何更改Perl语法以便只删除文件中最后一个匹配的单词而不是所有单词?

实施例

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

预期结果

more file

mark@$!
hgst#@
hhfdd@@

另一个例子

当 - 导出REPLACE_NAME ="标记@ $!"

hgst#@
hhfdd@@

预期结果

ec2-user

1 个答案:

答案 0 :(得分:1)

使用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;
  }
}