有没有办法在perl中用多行代替一个以START开头并以END结尾的字符串实例?
即。输入:
good
START
bad
bad
END
good
然后找到从START到END的范围,并替换为'被替换的':
good
replaced
good
非常感谢。
答案 0 :(得分:2)
使用旗帜。如下所示:
perl -ne '$inside = print "replaced\n" if /START/;
print unless $inside;
undef $inside if /END/' file
答案 1 :(得分:2)
您可以使用flip-flop ..
operator:
perl -pe '$_ = $i == 1 ? "replaced$/" : "" if $i = /START/ .. /END/' file
$i
计算从START
到END
的行,或者在外部开始结束时保留false值。
答案 2 :(得分:0)
这是一个简单的Perl程序,用于替换START和END之间的字符串(不区分大小写),如下面的代码所示:
#!/usr/bin/perl
use strict;
use warnings;
my $InFile = $ARGV[0];
my $document = do {
local $/ = undef;
open my $fh, "<", $InFile or die "Error: Could Not Open File $InFile: $!";
<$fh>;
};
$document =~ s/\bSTART\b.*?\bEND\b/replaced/isg;
print $document;