Friday, February 10, 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

2 comments:

  1. 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 :) .

    ReplyDelete
  2. Thanks for your post, your code is very useful :)

    ReplyDelete