My blog has moved!

You should be automatically redirected. If not, visit
http://benohead.com
and update your bookmarks.

Friday, March 23, 2012

Match context using grep / awk

With GNU grep you can use the -B <number> to set how many lines before the match and -A <number> for the number of lines after the match.

grep -B 1 -A 5 search_pattern filename

If you want the same number of lines before and after you can use -C <number> e.g.:

grep -C 2 search_pattern filename

This will show 2 lines before and 2 lines after the matched line.

or just -n (for n lines of context). -2 is quicker to type than -A 2 -B 2

if want to show all lines of output after the match? awk can do this:

awk '/search_pattern/,0' filename

On solaris, grep doesn't support any of these paramerters so you have to use awk:

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="search_pattern" filename

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

No comments:

Post a Comment