如何删除关键字前的行以及匹配字符串标记

时间:2016-10-28 07:56:46

标签: linux awk sed

我有一个这样的文件:

Sample text1 <TAG> some text
Line1
Line2
<INSERT>
Sample text3 <TAG> some text
Line3
<DELETE>
Sample text4 <TAG> some text
Line4
Line5
<INSERT>
Sample text5 <TAG> some text
Line6
<DELETE>

我想删除DELETE之前的行以及TAG之前的行,以便它看起来像这样:

Sample text1 <TAG> some text
Line1
Line2
<INSERT>
Sample text4 <TAG> some text
Line4
Line5
<INSERT>

2 个答案:

答案 0 :(得分:0)

您可以使用此awk

awk 'p&&/<TAG>/{p=0;next} !p&&/<TAG>/{p=1}p' file

<强>测试

$ awk 'p&&/<TAG>/{p=0;next} !p&&/<TAG>/{p=1}p' file
Sample text1 <TAG> some text
Line1
Line2
<INSERT>
Sample text4 <TAG> some text
Line4
Line5
<INSERT>

答案 1 :(得分:0)

在awk中使用我之前在评论中提到的解决方案:

$ cat foo.awk
/TAG/ { printf "%s", b; b="" }                       # at START output buffer and empty it
{ b=b $0 ORS }                                       # gather buffer
/DELETE/ { b="" }                                    # at empty buffer at END also

运行它:

$ awk -f foo.awk foo2
Sample text1 <TAG> some text
Line1
Line2
<INSERT>
Sample text4 <TAG> some text
Line4
Line5
<INSERT>