perl 单行
perl -i.BAK -pe 'if(/^SomeParameter/){s/B$/A/;$done=1}END{if(!$done){print"SomeParameter A\n"}} theFile
将创建备份 theFile.BAK(-i 选项)。一个更详细的版本,考虑到最后的评论,要测试。应保存在文本文件中并执行perl my_script.pl
或chmod u+x my_script.pl
./my_script.pl
#!/usr/bin/perl
use strict;
use warnings;
my $done = 0;
my $lastBeforeComment;
my @content = ();
open my $f, "<", "theFile" or die "can't open for reading\n$!";
while (<$f>) {
my $line = $_;
if ($line =~ /^SomeParameter/) {
$line =~ s/B$/A/;
$done = 1;
}
if ($line !~ /^#/) {
$lastBeforeComment = $.
}
push @content, $line;
}
close $f;
open $f, ">", "theFile.tmp" or die "can't open for writting\n$!";
if (!$done) {
print $f @content[0..$lastBeforeComment-1],"SomeParameter A\n",@content[$lastBeforeComment..$#content];
} else {
print $f @content;
}
close $f;
一旦确定,然后添加以下内容:
rename "theFile.tmp", "theFile"