我试图编写一个正则表达式来匹配特定的行并在它下面的行上执行操作。读取文件a.txt
的内容a.txt
I am from Melbourne .
Aussie rocks #The text can be anything below the first line
我正在编写一个正则表达式来读取文件,a.txt
并尝试替换下面的文本line 1
。片段:-
open($fh,"a.txt") or die "cannot open:$!\n";
while(<$fh>){
if($_=~/^I am from\s+.*/){
#I have to replace the line below it .
}
谁能帮帮我吗。我只需要replace a line below the line that matches my regex with an empty line or anything
。$line =~ s/<Line below line1>//;
。我怎样才能做到这一点 。?
有多种方法。
while (<$fh>) {
print;
if (/^I am from/) {
<$fh> // die "Expected line"; # discard next line
print "Foo Blargh\n"; # output something else
}
}
这是我的首选解决方案。
my $replace = 0;
while (<$fh>) {
if ($replace) {
print "Foo Blargh\n";
$replace = 0;
}
else {
print;
$replace = 1 if /^I am from/;
}
}
my $contents = do { local $/; <$fh> };
$contents =~ s/^I am from.*\ņ\K.*/Foo Blargh/m;
print $contents;
该正则表达式需要一个解释:^
匹配位于下方的行/m
。.*\n
与该行的其余部分匹配。\K
在匹配的子字符串中不包含前面的模式。的.*
下一行,然后将其替换为匹配Foo Blargh
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句