重击如何在标签之间获取多行文字 [英] Bash. How to get multiline text between tags

查看:75
本文介绍了重击如何在标签之间获取多行文字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在文件中的两个标签之间获取文本.但是,如果脚本找到了开始标签而没有找到结束标签,则它将文件从开始标签打印到文件的末尾.

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.

例如,文字为:

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

和类似这样的脚本:

awk "/TAG1/,/TAG2/"

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

比输出将是:

some right text
some text3
some text4

但是我需要这个:

some right text

推荐答案

切勿使用范围表达式,因为它们会使微不足道的任务变得更简短,但是当事情变得更加有趣时,则需要完全重写以避免重复的条件,例如您的情况.始终改用标志:

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

这篇关于重击如何在标签之间获取多行文字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆