How to print lines between pattern1 and 2nd match of pattern2

awksedtext processing

Test file is given below:

PATTERN1
a
b
c
PATTERN2
d
e
f
PATTERN2
g
h

I want to print line between PATTERN1 and 2nd match of PATTERN2:

PATTERN1
a
b
c
PATTERN2
d
e
f
PATTERN2

Best Answer

Here's one way to do it with sed:

sed '/PATTERN1/,$!d;/PATTERN2/{x;//{x;q;};g;}' infile

This just deletes all lines (if any) up to the first occurrence of PATTERN1 and then, on each line that matches PATTERN2 it exchanges buffers. If the new pattern space also matches, it means it's the 2nd occurrence so it exchanges back and quits (after auto-printing). If it doesn't match it means it's the 1st occurrence so it copies the hold space content over the pattern space via g (so now there's a line matching PATTERN2 in the hold buffer) and goes on...
and another way with awk:

awk '/PATTERN1/{t=1}; t==1{print; if (/PATTERN2/){c++}}; c==2{exit}' infile

It starts printing and counting lines matching PATTERN2 only when encountering a line matching PATTERN1 and exits when counter reaches 2.

Related Question