如何在 Perl 中删除正则表达式匹配后的行
how to delete the line after a regex match in Perl
我想在正则表达式匹配后删除该行,但我不确定如何编写代码以在 Perl 中删除下一行 - 求助?
while ( my $line = <FILE> ) {
if ($line =~ m/(regex)/i) {
# delete the next $line
}
你是什么意思"delete"?你是说忽略它?
while ( my $line = <FILE> ) {
if ( $line =~ /regex/ ) { # If it matches this regex
my $ignored = <FILE>; # read the next line and ignore it.
}
}
遇到匹配时设置 $skip_flag
怎么样?当您逐行读取文件时,您可以构建输出字符串,在设置标志时跳过行。
if ( $line =~ /regex/ ) { # If it matches this regex
<FILE>; # gobble gobble
}
朋友,你需要的就是这些。
你可以运行$> perl -pi -e 'BEGIN{undef $/;} s#(YOUR_REGEX_PATTERN)[^\n]*\n[^\n]*\n#\n#' YOUR_FILE
这可以做到multiline replacement by forcing Perl to read the entire file at once。
但是总是一定要先备份!您可以让 Perl 为您完成 appending a suffix 到 -i
开关,例如 $> perl -pi.bak -e ...
我想在正则表达式匹配后删除该行,但我不确定如何编写代码以在 Perl 中删除下一行 - 求助?
while ( my $line = <FILE> ) {
if ($line =~ m/(regex)/i) {
# delete the next $line
}
你是什么意思"delete"?你是说忽略它?
while ( my $line = <FILE> ) {
if ( $line =~ /regex/ ) { # If it matches this regex
my $ignored = <FILE>; # read the next line and ignore it.
}
}
遇到匹配时设置 $skip_flag
怎么样?当您逐行读取文件时,您可以构建输出字符串,在设置标志时跳过行。
if ( $line =~ /regex/ ) { # If it matches this regex
<FILE>; # gobble gobble
}
朋友,你需要的就是这些。
你可以运行$> perl -pi -e 'BEGIN{undef $/;} s#(YOUR_REGEX_PATTERN)[^\n]*\n[^\n]*\n#\n#' YOUR_FILE
这可以做到multiline replacement by forcing Perl to read the entire file at once。
但是总是一定要先备份!您可以让 Perl 为您完成 appending a suffix 到 -i
开关,例如 $> perl -pi.bak -e ...