我试图编写一个正则表达式来匹配一个特定的行,并在它下面的行上执行操作。读取文件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>//;
。我怎么能这么做呢?
发布于 2014-01-07 02:46:34
有很多种方法。
阅读循环中的下一行:
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;
这个regex需要一个解释:^
与/m
下的行开始匹配。.*\n
与行的其余部分匹配。\K
在匹配的子字符串中不包括前面的模式。.*
匹配下一行,然后由Foo Blargh
替换。
发布于 2014-01-07 02:40:10
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;
https://stackoverflow.com/questions/20969374
复制相似问题