how to grep and print the next N lines after the hit?

15

3

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

719016

Posted 2011-06-16T15:46:53.117

Reputation: 2 899

Answers

22

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.

Colin K

Posted 2011-06-16T15:46:53.117

Reputation: 336

7

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

geekosaur

Posted 2011-06-16T15:46:53.117

Reputation: 10 195

1awk '/regex/{p=2} p > 0 {print $0; p--}' filename - works, yours not. – BladeMight – 2019-03-03T12:25:32.743

4

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

Ignacio Vazquez-Abrams

Posted 2011-06-16T15:46:53.117

Reputation: 100 516

3

Print N lines after matching lines

You can use grep with -A n option to print N lines after matching lines.

For example:

$ cat mytext.txt 
  Line1
  Line2
  Line3
  Line4
  Line5
  Line6
  Line7
  Line8
  Line9
  Line10

$ grep -wns Line5 mytext.txt -A 2
5:Line5
6-Line6
7-Line7

Other related options:

Print N lines before matching lines

Using -B n option you can print N lines before matching lines.

$ grep -wns Line5 mytext.txt -B 2
3-Line3
4-Line4
5:Line5

Print N lines before and after matching lines

Using -C n option you can print N lines before and after matching lines.

$ grep -wns Line5 mytext.txt -C 2
3-Line3
4-Line4
5:Line5
6-Line6
7-Line7

user1336087

Posted 2011-06-16T15:46:53.117

Reputation: 148