Grep for a word in a file and show below and above lines too?

9,511

Suppose your file is called filename, your regular expression is foo, and you want to print matching lines and lines within 10 lines (above and below) matching lines:

grep -C10 foo filename

More generally, for n lines before and after matches:

grep -Cn foo filename

This solution will work with GNU grep (which Ubuntu and just about every other Linux-based operating system has). The -C flag is not necessarily supported in all grep implementations, though.

To print lines only before or only after matches, use the -Bn or -An switches respectively, where n is the number of lines you want before or after. For more information about an alternative way to do it, see this related question (kudos to fossfreedom for noticing the similarity).

Share:
9,511

Related videos on Youtube

David
Author by

David

Updated on September 18, 2022

Comments