Nov 10, 2018

How to output additional adjacent / surrounding lines when using Grep command in Linux

Use -B num to set how many lines before the match and -A num for the number of lines after the match.

grep -B 3 -A 2 mySearchTxt MyFile.txt

If you want the same amount of lines before and after you can use -C num.

grep -C 8 mySearchTxt MyFile.txt

This will show 8 lines before and 8 lines after.

Or you can just -n:

grep -8 mySearchTxt MyFile.txt