"grep and display few lines before and after"

Post #302098992 by Ygor on Thursday 7th of December 2006 06:38:57 PM

Old 12-07-2006
Try...
Code:
nawk 'c-->0;$0~s{if(b)for(c=b+1;c>1;c--)print r[(NR-c+1)%b];print;c=a}b{r[NR%b]=$0}' b=2 a=4 s="string" file1

...where "b" and "a" are the number of lines to print before and after string "s".

---edit----

It's not the best generic solution because it can't handle the case if the search string is repeated in the "before" lines.

A better way...
Code:
nawk '$0~s{for(c=NR-b;c<=NR+a;c++)r[c]=1}{q[NR]=$0}END{for(c=1;c<=NR;c++)if(r[c])print q[c]}' b=2 a=4 s="string" file1

...where "b" and "a" are the number of lines to print before and after string "s".

Last edited by Ygor; 05-31-2012 at 07:51 AM.. Reason: Had to update this post because my buggy code is propagating all over the internet.
These 6 Users Gave Thanks to Ygor For This Post:
doublefrangelic (10-18-2010) mad man (01-25-2016) nariwithu (01-25-2012) nes (11-28-2013) shandrio (07-23-2012) Sionnagh (10-06-2014)