Denis Nek Denis Nek - 3 months ago 15
Bash Question

Bash. How to get multiline text between tags

I'm trying to get text in my file between two tags. But if script finds opening tag and do not finds closing tag then it prints file from opening tag to the file's end.

For example text is:

aaa
TAG1
some right text
TAG2
some text2
TAG1
some text3
some text4


and script like this:

awk "/TAG1/,/TAG2/"


or

sed -n "/TAG1/,/TAG2/p"


than output will be:

some right text
some text3
some text4


but I need this:

some right text

Answer

Never use range expressions as they make tirivial tasks slightly briefer but then need a complete rewrite to avoid duplicate conditions when things get even slightly more interesting, as in your case. Always use a flag instead:

$ awk 'f{ if (/TAG2/){printf "%s", buf; f=0; buf=""} else buf = buf $0 ORS}; /TAG1/{f=1}' file
some right text
Comments