grep -v pattern and also remove 1 line before and

2019-06-25 06:00发布

问题:

This question is an exact duplicate of:

  • How to exclude several lines around match with grep or similar tool? 1 answer

I would like to grep a pattern and remove the line of the matching pattern and also 1 line before and 4 lines after the context. I tried:

grep -v -A 4 -B 1

Thanks in advance!

Example:

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.......

I would like to grep "explorer.exe" and remove the line and also 1 line before and 4 lines after.

回答1:

awk

this awk one-liner would help:

 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

see this example:

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

if vim is also possible for you, it could be a lot easier:

:g/Pattern/norm! k6dd

Note, the vim solution would have problem in first match if your pattern was on the 1st line in your file.