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. See the nice solution provided by Ygor:

2 thoughts on “Match context using grep / awk

    1. I didn’t know where I had this code from. Now I have the link, I’ve replaced the code by the link. Thanks for the great solution on solaris !

Leave a Reply

Your email address will not be published.