Grep for a word in a file and show below and above lines too?
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).
Related videos on Youtube
David
Updated on September 18, 2022Comments
-
David almost 2 years
Possible Duplicate:
How to grep 2 or 3 lines, one containing the text I want, and the others just below it?Say I have a file. I want to find a particular word in that file and show the line.
Is there a way I can do the above, but also include the above and below 10 lines from the result line?
How would I do this using the Linux command line?