Print lines of a file between two matching patterns

You can make sed quit at a pattern with sed '/pattern/q', so you just need your matches and then quit at the second pattern match:

sed -n '/^pattern1/,/^pattern2/{p;/^pattern2/q}'

That way only the first block will be shown. The use of a subcommand ensures that ^pattern2 can cause sed to quit only after a match for ^pattern1. The two ^pattern2 matches can be combined:

sed -n '/^pattern1/,${p;/^pattern2/q}'

As a general approach, with sed, it's easy to print lines from one match to another inclusively:

$ seq 1 100 > test
$ sed -n '/^12$/,/^15$/p' test
12
13
14
15

With awk, you can do the same thing like this:

$ awk '/^12$/{flag=1}/^15$/{print;flag=0}flag' test
12
13
14
15

You can make these non-inclusive like this:

$ awk '/^12$/{flag=1;next}/^15$/{flag=0}flag' test
13
14

$ sed -n '/^12$/,/^15$/p' test | sed '1d;$d'
13
14

Tags:

Grep

Awk

Sed