Last Updated: February 25, 2016
·
1.069K
· peterjmit

Show the surrounding lines for grep matches

Have you ever wanted to see the lines immediately above/below your matches when you're using grep?

grep has three modifiers that can help you out

Use -A <num> to specify the number of lines to show after the match

grep -A 5 "Search term" file.txt

Use -B <num> to specify the number of lines to show before the match

grep -B 2 "Search term" file.txt

You can use -A <num> and -B <num> together

grep -A 5 -B 2 "Search term" file.txt

OR

Use -C <num> to specify an equal number of lines to show above & below the match

grep -C 10 "Search term" file.txt