How to display lines 2-4 after each grep result?

The simplest way to solve it using grep only, is to pipe one more inverted grep at the end. For example:

grep -A 4 "The mail system" temp.txt | grep -v "The mail system" | grep -v '^\d*$'

If you aren't locked in to using grep, try sed ...

sed -n '/The mail system/{n;n;p}' 

When it finds a line containing "The mail system", it reads the next line twice, via the n;n;, discarding each previous line as it does so.
This leaves the 3rd line of your group in the pattern space, which is then printed via sed's p command.. The leading -n option prevents all other printing.

To print the next two lines as well, it is just a case of next and print n;p twice more.

sed -n '/The mail system/{n; n;p; n;p; n;p}'   

The next-line reads for the lines you require can be accumulated and printed a a single block with just one p... N reads the next line and appends it to the pattern space,

Here is the final condensed version...

sed -n '/The mail system/{n;n;N;N;p}'   

If you want a group seperator, similar to what grep wouuld output, you can use sed's insert command i (which must be the last command on a line)...

Here is the syntax to include a group seperator

sed -n '/The mail system/{n;n;N;N;p;i--
       }' > output-file  # or | ...

Here is the output for the first match:

<[email protected]>: host mx1.hotmail.com[65.54.188.94] said: 550
    Requested action not taken: mailbox unavailable (in reply to RCPT TO
    command)                                                                    
--

grep -A 2 -B -2 "The mail system" mbox_file

-B is for previous lines, so no need to give -negative value.

grep -A 2 -B 2 "The mail system" mbox_file   # This will work please check

Tags:

Grep