How to print all lines after second match?

Viewed 767
awk -vN=2 'n>=N;/last pid.*/{++n}' file

I'd like to print out all lines after the second regex match, including the line that contains the regex. This is close but it doesn't print out the line containing the regex. Any quick help with this?

Example Input

last pid: something
blah
blah
last pid: something else
this
is
what
i
want

Desired Output:

last pid: something else
this
is
what
i
want
2 Answers

You just need to reverse the order of the statements:

$ awk -vN=2 '/last pid/{++n} n>=N' file
last pid: something else
this
is
what
i
want

Also, the .* in /last pid.*/ is superfluous. Anything that matches /last pid.*/ will match /last pid/ and vice versa.

awk solution:

$ cat tst.awk
/last pid/ { p++ }         # if you see a last pid, add 1 to p
p < N {next}1              # whenever p smaller than N, skip.
                           # else print

call this with:

awk -v N=2 -f tst.awk input.txt

which gives:

$ awk -v N=2 -f tst.awk input.txt
last pid: something else
this
is
what
i
want

or oneliner:

$ awk -v N=2 '/last pid/ { p++ }p < N {next}1' input.txt
Related