Linux sed – Print Lines Between Start and End Pattern

linuxsed

I'm looking to find the lines between two matching patterns. If any start or end pattern missing, lines should not print.

Correct input:

a
***** BEGIN *****
BASH is awesome
BASH is awesome
***** END *****
b

Output will be

***** BEGIN *****
BASH is awesome
BASH is awesome
***** END *****

Now suppose END pattern is missing in input

a
***** BEGIN *****
BASH is awesome
BASH is awesome
b

Lines should not print.

I have tried with sed:

sed -n '/BEGIN/,/END/p' input

It prints all data up to the last line if END pattern is missing.

How to solve it?

Best Answer

cat input |
sed '/\*\*\*\*\* BEGIN \*\*\*\*\*/,/\*\*\*\*\* END *\*\*\*\*/ p;d' | 
tac |
sed '/\*\*\*\*\* END \*\*\*\*\*/,/\*\*\*\*\* BEGIN *\*\*\*\*/ p;d' |
tac

It works by having tac reverse the lines so that sed can find both delimiters in both orders.

Related Question