I would like to grep for an occurrence in a text file, then print the following N lines after each occurrence found. Any ideas?

link|improve this question

73% accept rate
feedback

3 Answers

up vote 6 down vote accepted

Grep has the following options that will let you do this (and things like it). You may want to take a look at the man page for more information:

  • -A num Print num lines of trailing context after each match. See also the -B and -C options.

  • -B num Print num lines of leading context before each match. See also the -A and -C options.

  • -C[num] Print num lines of leading and trailing context surrounding each match. The default is 2 and is equivalent to -A 2 -B 2. Note: no whitespace may be given between the option and its argument.

link|improve this answer
feedback

If you have GNU grep, it's the -A/--after-context option. Otherwise, you can do it with awk.

awk '/regex/ {p = N}
     p > 0   {print $0; p--}' filename
link|improve this answer
feedback

Use the -A argument to grep to specify how many lines beyond the match to output.

link|improve this answer
feedback

Your Answer

 
or
required, but never shown

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