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
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
:This just deletes all lines (if any) up to the first occurrence of
PATTERN1
and then, on each line that matchesPATTERN2
it ex
changes buffers. If the new pattern space also matches, it means it's the 2nd occurrence so it ex
changes back andq
uits (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 viag
(so now there's a line matchingPATTERN2
in the hold buffer) and goes on...and another way with
awk
:It starts printing and counting lines matching
PATTERN2
only when encountering a line matchingPATTERN1
and exits whenc
ounter reaches2
.