You're viewing a comment by Jotne and its responses.

Jotne Permalink
August 14, 2013, 07:39

Print 2 lines before and 3 after "pattern"

awk '{a[NR]=$0} $0~s {f=NR} END {for (i=f-B;i<=f+A;i++) print a[i]}' B=2 A=3 s="pattern"<\code>
grep -A3 -B2 "pattern"<\code>

Comment Responses

Sheetal Permalink
May 17, 2016, 06:23

Hi Jotne,

I have used the below command to search for a pattern and remove the 5 lines before and 7 lines after the pattern:

awk '/pattern/{for(x=NR-5;x<=NR+7;x++)d[x];}{a[NR]=$0}END{for(i=1;i<=NR;i++)if(!(i in d))print a[i]}' filename

This is working as expected.

But I was not clear on the logic used.

Would you be able to help me understand the logic?

Thanks,
Sheetal

Reply To This Comment

(why do I need your e-mail?)

(Your twitter name, if you have one. (I'm @pkrumins, btw.))

Type the word "disk_100": (just to make sure you're a human)

Please preview the comment before submitting to make sure it's OK.