Ask Ubuntu is a question and answer site for Ubuntu users and developers. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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?

share|improve this question

marked as duplicate by bodhi.zazen, jokerdino, Eliah Kagan, Nitin Venkatesh, izx Aug 17 '12 at 23:53

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

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|improve this answer

Not the answer you're looking for? Browse other questions tagged or ask your own question.