Print line X lines before/after found line

awkgrepsed

I want to search for a particular string in a certain file. If I found the string, I also want to print the line X lines before (or after) that line.

Can this with grep or awk, or do I need a combination?

I would like to have something like this, but not with all trailing/leading lines before or after a hit, only the Xth.

For example, if my input looks like:

line1 with a pattern
line2
line3
line4 with a pattern
line5
line6
line7 with a pattern
...

I e.g. want to search for the word 'pattern' and output that line + the line that is 2 lines after that, but not the line that directly follows the line with the pattern. So the desired output is:

line1 with a pattern
line3
line4 with a pattern
line6
line7 with a pattern
...

Best Answer

grep will do this for you, with options -A (after) and -B (before), and -C (context). An example I often use is:

   sudo lspci -vnn | grep -i net -A 12

because this command will show 12 lines after the match, which includes the driver used to control the network (-i net) card. In general, the command is:

  grep text_to_search -A n -B m file.extension

which will output m lines before the match, and n lines after the match. Or you can use

 grep text_to_search -C n file.extension

to show a total of n lines surrounding the text found (half before, half after the match).

Related Question