Saturday, February 11, 2012

Print 3 lines before and 5 lines after pattern match abcd in a file a.txt

In Linux:

awk '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=3 a=5 s="abcd" a.txt

In SOLARIS:

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=3 a=5 s="abcd" a.txt

4 comments:

Rajeev said...

grep -B3 file
grep -A5 file

Manu Swami said...

grep will do in below way:

grep -B3 -A5 "pattern" filename

However in case of bulky files one may require to opt for awk/sed :) .

Jorge N. said...

Thanks for your post, your code is very useful :)

Unknown said...

It was very nice article and it is very useful to Linux learners.We also provide Linux online training

 

Blogger news

Blogroll