【问题标题】:grep -v pattern and also remove 1 line before and 4 lines after [duplicate]grep -v 模式并删除之前的 1 行和之后的 4 行 [重复]
【发布时间】:2015-02-20 08:58:50
【问题描述】:

我想 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 行。

【问题讨论】:

  • 一个示例以及预期的输出会更好。
  • 这是 yarascan 在 Volatility 中的标准输出格式。

标签: regex bash shell awk grep


【解决方案1】:

awk

这个 awk 单行代码会有所帮助:

 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

注意,如果您的pattern 位于文件的第一行,vim 解决方案将在第一次匹配时出现问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-03-15
    • 2013-10-01
    • 2014-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多