How to grep 2 or 3 lines, one containing the text I want, and the others just below it?

Just do a:

grep -A1 ERROR

The -A1 tells grep to include 1 line after the match. -B includes lines before the match, in case you need that too.


For a more portable way, there's awk

awk '/ERROR/{n=NR+1} n>=NR' foo.log

Or maybe you want all the indented lines following?

awk '/^[^[:blank:]]/{p=0} /ERROR/{p=1} p' foo.log

I have found this solution:

cat apache.error.log | grep -Pzo '^.*?Exception In get Message.*?\ncom\.rabbitmq.*?(\n(?=\s).*?)*$'

Where (\n(?=\s).*?)* means:

  • \n find next line
  • (?=\s) where is starts from whitespace character
  • .*? until end of line
  • (...)* Find such lines multiple times

PS. You may turf this pattern \ncom\.rabbitmq.*? if second line begins from whitespace \s