对于小文件,可以翻转后正序删除
tac file | sed '/tom/I,+2 d' | tac #即删除不区分大小写匹配到有tom的行,同时删除向上两行
grep
grep
-A 2 匹配后继续向下打印2行
-B 2 匹配后继续向上打印2行
-C 2 向上向下各打印2行
awk
下面awk脚本可删除指定具体匹配行的前n行
#!/bin/sh
# grep-ac: a grep-like awk script
# Arguments: pattern = awk regexp to search for
# before = number of lines to print before a match
# after = number of lines to print after a match
{ "exec" "awk" "-f" "$0" "$@"; }
# The array h contains the history of lines that haven't been printed
# but are eligible for being "before" lines.
# The variable until contains the number of the last "after" line to print.
match($0, pattern) { # the current line matches
for (i in h) {
print h[i]; # print each remaining before line
delete h[i]; # delete each line as it's printed
}
until=NR+after; # record the last after line to print
}
{
if (NR<=until) print $0; # from a match to its last after line: print
else h[NR]=$0; # after that: save in history
delete h[NR-before]; # remove line too old to be a before line
}
END {exit !until} # exit status: 0 if there was a match, else 1
cat who.txt | ./dbefor.sh -vbefore=2 -vpattern='tom'
vim(ex模式)
vim -e -c 'g/tom/.-2,.d' -c 'wq' file #命令上运行,删除匹配到包括tom的前3行
perl 滑动窗口
待学习
perl -ne 'push @lines, $_;
splice @lines, 0, 3 if /tom/;
print shift @lines if @lines > 2
}{ print @lines;' #删除匹配到包括tom的前3行
sed
sed -e:b -e '$!{N;2,5bb' -e\} -e'/\n.*match/!P;D' #删除匹配match的前5行
.sed -i -e '/string/{n;d}' -e '$!N;/\n.*string/!P;D' file #删除匹配行的上一行和下一行:
参考https://blog.csdn.net/lovedingd/article/details/106541466
https://www.gnu.org/software/sed/manual/sed.html#Hold-and-Pattern-Buffers