linux 处理匹配文本的前后行

对于小文件,可以翻转后正序删除

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

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值