加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

正则表达式 – grep -v模式并删除之前的1行和之后的4行

发布时间:2020-12-14 05:57:03 所属栏目:百科 来源:网络整理
导读:这个问题与以下内容完全相同:???????????????????????? How to exclude several lines around match with grep or similar tool?????????????????????????????????????1个 我想grep一个模式并删除匹配模式的行,并且还在上下文之前的1行和4行之后.我试过了:
这个问题与以下内容完全相同:????????????>???????????? How to exclude several lines around match with grep or similar tool?????????????????????????????????????1个
我想grep一个模式并删除匹配模式的行,并且还在上下文之前的1行和4行之后.我试过了:

grep -v -A 4 -B 1

提前致谢!

例:

Rule: r1
Owner: Process explorer.exe Pid 1544
0x01ec350f  8b 45 a8 0f b6 00 8d 4d a8 ff 14 85 c8 7f ed 01   .E.....M........
0x01ec351f  84 c0 75 ec 8b 4d fc e8 ba f5 fe ff f7 85 b0 fd   ..u..M..........
0x01ec352f  ff ff 00 00 01 00 75 13 33 c0 50 50 50 68 48 28   ......u.3.PPPhH(
0x01ec353f  eb 01 33 d2 8b cb e8 b0 57 ff ff f7 05 8c 9b ed   ..3.....W.......

我想grep“explorer.exe”并删除该行,之前还有1行和4行之后.

解决方法

AWK

这个awk one-liner会有所帮助:

awk  'NR==FNR{if(/explorer[.]exe/)d[++i]=NR;next}
      {for(x=1;x<=i;x++)if(FNR>=d[x]-1&&FNR<=d[x]+4)next}7' file file

看这个例子:

kent$ cat f
foo
foo2
Rule: r1
Owner: Process explorer.exe Pid 1544
remove1
remove2
remove3
remove4
bar
bar2

kent$ awk  'NR==FNR{if(/explorer[.]exe/)d[++i]=NR;next}{for(x=1;x<=i;x++)if(FNR>=d[x]-1&&FNR<=d[x]+4)next}7' f f 
foo
foo2
bar
bar2

VIM

如果你也可以使用vim,那可能会容易得多:

:g/Pattern/norm! k6dd

注意,如果您的模式位于文件的第一行,则vim解决方案在第一次匹配时会出现问题.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读