[英]Regular Expressions in Perl
我試圖編寫一個正則表達式來匹配特定的行,並在它下面的行上執行操作。 讀文件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>//;
。 我怎樣才能做到這一點 。?
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;
有多種方法。
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
替換。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.