【问题标题】:How to remove lines before the keyword and up to its match string tag [duplicate]如何删除关键字之前的行及其匹配字符串标签[重复]
【发布时间】:2016-10-28 18:15:33
【问题描述】:

我有一个这样的文件:

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>

【问题讨论】:

  • 获取上一个问题的解决方案,并将关键字从START 和END 更改为TAG 和DELETE。注意:我只测试了我的解决方案并且它有效。
  • @JamesBrown,是的,当你这样说时,这将完全重复。起初我以为OP想在&lt;INSERT&gt;之后立即从行中删除,包括&lt;DELETE&gt;
  • @JamesBrown 这与我之前的问题不同。我的问题出在标签中,因为所有插入、删除、更新都具有相同的起始标签。所以我不能使用 sed '/TAG/,/DELETE/d' 因为它会删除第 1 行到第 5 行。
  • @Bootsector 就像我说的,您也可以使用我对您上一个问题的解决方案来解决这个问题。如果问题真的不同,也许你应该在问题中强调这一点 - 同时展示你为解决问题所做的努力。
  • @JamesBrown 抱歉,我没有注意到您对我上一个问题的回答。是的,您的解决方案确实有效。谢谢!

标签: linux awk sed


【解决方案1】:

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

$ 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>

【讨论】:

    【解决方案2】:

    你可以使用这个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>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-07-11
      • 2020-04-05
      • 2011-02-04
      • 2015-12-25
      • 1970-01-01
      • 1970-01-01
      • 2016-08-30
      • 2022-11-21
      相关资源
      最近更新 更多