Bash – How to read certain lines after a find some text

bashshell

How i can read a certain number of lines after find some text?

Eg.:

Read next 2 lines after find "Unix" on:

Test 1
Test 2
Test 3
Test 4
UNIX
Test 5
Test 6
Test 7
Test 8
Test 9

Result can be:

Test 5
Test 6

Note: The "Unix" on last example is an argument, and so, it can be any other text.

What i have:

I'm still out of ideas, need just a light. Thinking on create another script to do that.

Best Answer

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.

Related Question