How to read certain lines after a find some text?

A grep solution:

grep -A2 -P '^UNIX$' file

Explanation: -A means: print the next two lines after the match

Or awk:

awk '$0=="UNIX"{getline; print; getline; print}' file

Explanation: Search for UNIX in the line ($0=="UNIX"). If found, get the next line into the buffer (getline) and print the buffer (print). This is done twice.

Or use sed:

sed -n '/^UNIX$/{n;p;n;p}' file

Explanation: Search for UNIX (/^UNIX$/). If found, execute the part in the {...}. n means next, p means print. This is done twice as well.


An awk solution:

$ awk '$0 == "UNIX" {i=1;next};i && i++ <= 2' file
Test 5
Test 6

Explanation

  • /^UNIX$/{i=1;next}: if we see UNIX, we set variable i = 1, processing to next input.

  • If variable i is set (meaning we saw UNIX), i && i++ <= 2 only evaluated to true value in next two lines after UNIX, causing awk performed default action print $0.

  • Before seeing UNIX, i was not defined and begin at 3rd line after UNIX, i had a value greater than 2, which make expression i && i++ <= 2 evaluated to false, causing awk do nothing.


grep -A 2 UNIX file.txt

The manpage of grep describes the option thus:

  -A NUM, --after-context=NUM
      Print NUM  lines  of  trailing  context  after  matching  lines.
      Places  a  line  containing  --  between  contiguous  groups  of
      matches.

Tags:

Shell

Bash