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 thought on “Shell – How to get surrounding lines of grep result?”

Leave a Reply