How can I use sed to match between two patterns and get the next line after the second pattern?

Viewed 170

I'm familiar with using sed to grab lines between two patterns. For example:

$ cat file
A
PATTERN1
B
PATTERN2
C
$ sed -n '/PATTERN1/,/PATTERN2/p' file
PATTERN1
B
PATTERN2

What I'd like to do, however, is generate this output:

PATTERN1
B
PATTERN2
C

I've come across the {n;p} syntax (example), but I can't seem to shoehorn this into the type of pattern matching I'm doing in this example problem.

2 Answers

This might work for you (GNU sed):

sed -n '/PATTERN1/,/PATTERN2/{p;/PATTERN2/{n;p}}' file

Alternative:

sed '/PATTERN1/{:a;n;/PATTERN2/!ba;n;p};d' file
Related