删除多个文件中模式后的行

remove lines after pattern in multiple files

我有以下命令

find ./ -type f -exec perl -pi -e 's/<pattern>//g' '{}' \;

它运行良好并删除了模式,但是如何删除模式、它所在的行以及之后的 n 行?

取一个文件:

aaa
bbb
ccc
ddd
eee
fff

现在,我们要从 bbb 删除到 ccc,所以 :

perl -i -0pe 's/bbb.*ccc//ms'  file

0 逐段 文件

它比优雅更暴力,但我认为这将删除具有匹配模式的行及其后的行。

find ./ -type f -exec perl -i -e '$x=0 ; while (<>) {if ($_ =~ /<pattern>/) { $x++; next; }; if ($x) { $x=0; next; }; print "$_";}' {} \;

这只是一个文件的 perl 答案。我不希望任何发现此问题的人都没有意识到您将其包装在其中的 find 也会编辑隐藏文件。

答案:

perl -ni -e '$ml=$. if /<pattern>/; print unless (defined $ml && $.<=$ml+[n])' input-file

解释:

perl -ni 将读取并替换 input-file 但仅在指示

时打印

$ml=$. if /<pattern>/设置$ml匹配行变量为$.,也就是输入文件的当前行

print unless (defined $ml && $.<=$ml+[n]) 将打印除匹配行和下 [n] 行之外的每一行