如何打印匹配的行及其前后的行?我目前有:
perl -lane 'print if $F[3] > 100000 && $F[2] =~ /^C$/ && print $last; $last = $_'
它能够打印匹配的行和它之前的行 - 但我不确定如何包含之后的行。
最佳答案
您可以使用scalar <>
直接从文件中读取下一行。 :
perl -lane 'print, print scalar <>
if $F[3] > 100000 && $F[2] =~ /^C$/
&& print $last;
$last = $_' input
或者使用滑动窗口进行重叠匹配:
perl -ane 'BEGIN { @b = map [], 1 .. 3 }
sub out {
shift @b;
if ($b[1][3] > 100_000 && $b[1][2] =~ /^C$/) {
print for map $_->[-1], @b;
}
}
push @b, [@F, $_];
out()
}{ out() # Process the last line
' input
关于regex - 在正则表达式匹配时打印匹配的行和行±1(1行),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33695234/