Bash. How to get multiline text between tags

2019-03-06 06:12发布

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

1条回答
姐就是有狂的资本
2楼-- · 2019-03-06 06:37

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
查看更多
登录 后发表回答