Categories
Tech Notes

Shell – How to get surrounding lines of grep result?

Problem:
I'm using grep to search for an error and want to display the surrounding lines also as they contain related information. How to do that?

Solution:
Using grep -C <# of lines to show above and below> <search> <file>

The following prints the matched line, along with the 5 lines surrounding it.

$ grep -C 5 "search" sample_text

Also we can use grep -A or -B to display number of lines above or below the matched line.

The following prints the matched line, along with the 5 lines after it.

$ grep -A 5 "search" sample_text

The following prints the matched line, along with the 5 lines before it.

$ grep -B 5 "search" sample_text

Reference:

One reply on “Shell – How to get surrounding lines of grep result?”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s