Sed – How to Select First Occurrence Between Two Patterns

awkregular expressionsed

How can I select first occurrence between two patterns including them. Preferably using sed or awk.

I have:

text
something P1 something
content1
content2
something P2 something
text
something P1 something
content3
content4
something P2 something
text

I want the first occurrence of the lines between P1 and P2 (including P1 line and P2 line):

something P1 something
content1
content2
something P2 something

Best Answer

sed '/P1/,/P2/!d;/P2/q'

...would do the job portably by deleting all lines which do !not fall within the range, then quitting the first time it encounters the end of the range. It does not fail for P2 preceding P1, and it does not require GNU specific syntax to write simply.

Related Question