我正在尝试编写正则表达式以匹配特定行并在其下方的行上执行操作。阅读文件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>//;
。我怎样才能做到这一点 。?
答案 0 :(得分:2)
open(my $fh, "<", "a.txt") or die $!;
my $replace;
while(<$fh>){
$_ = "\n" if $replace;
$replace = /^I am from.*/;
print;
}
或立即阅读文件,
open(my $fh, "<", "a.txt") or die $!;
my $str = do { local $/; <$fh> };
$str =~ s/^I am from.*\n \K .*//xm;
print $str;
答案 1 :(得分:1)
有种方式。
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
替换。