【问题标题】:Remove string after match along with the word/string after that匹配后删除字符串以及之后的单词/字符串
【发布时间】:2020-07-11 06:34:03
【问题描述】:

我有一个包含以下模式行的文件。

date=2020-02-22 time=13:32:41 type=text subtype=text ip=1.2.3.4 country="China" service="foo"  id=47291 msg="foo: bar.baz," value=50
date=2020-03-17 time=11:49:54 type=text subtype=anothertext ip=1.2.3.5 country="Russian Federation" service="bar"  id=47324 msg="foo: bar.baz," value=30
date=2020-03-30 time=16:29:24 type=text subtype=someothertext ip=1.2.3.6 country="Korea, Republic of" service="grault, garply"  id=47448 msg="foo: bar.baz," value=60

我想删除类型、子类型和服务以及这些字段的值(= 之后的值)。

期望的输出:

date=2020-02-22 time=13:32:41 ip=1.2.3.4 country="China" id=47291 msg="foo: bar.baz," value=50
date=2020-03-17 time=11:49:54 ip=1.2.3.5 country="Russian Federation" id=47324 msg="foo: bar.baz," value=30
date=2020-03-30 time=16:29:24 ip=1.2.3.6 country="Korea, Republic of" id=47448 msg="foo: bar.baz," value=60

在知之甚少的情况下,我一直在尝试使用cutawksed,但仍然没有接近解决方案。我已经在网上搜索了几个小时,但这也徒劳无功。有人可以帮忙吗?

【问题讨论】:

    标签: bash awk sed cut


    【解决方案1】:

    您以后可能想要重用或构建的东西:

    $ cat tst.awk
    BEGIN {
        split(s,tmp)
        for (i in tmp) {
            skip[tmp[i]]
        }
        FPAT = "[^ ]+(=\"[^\"]+\")?"
    }
    {
        c=0
        for (i=1; i<=NF; i++) {
            tag = gensub(/=.*/,"",1,$i)
            if ( !(tag in skip) ) {
                printf "%s%s", (c++ ? OFS : ""), $i
            }
        }
        print ""
    }
    
    $ awk -v s='type subtype service' -f tst.awk file
    date=2020-02-22 time=13:32:41 ip=1.2.3.4 country="China" id=47291 msg="foo: bar.baz," value=50
    date=2020-03-17 time=11:49:54 ip=1.2.3.5 country="Russian Federation" id=47324 msg="foo: bar.baz," value=30
    date=2020-03-30 time=16:29:24 ip=1.2.3.6 country="Korea, Republic of" id=47448 msg="foo: bar.baz," value=60
    

    上面使用 GNU awk 进行 FPAT 和 gensub()。

    【讨论】:

      【解决方案2】:

      你可以使用这个sed:

      sed -E 's/(^|[[:blank:]]+)(subtype|type|service)=[^[:blank:]]+//g' file
      

      date=2020-02-22 time=13:32:41 ip=1.2.3.4 country="China"  id=47291 msg="foo: bar.baz," value=50
      date=2020-03-17 time=11:49:54 ip=1.2.3.5 country="Russian Federation"  id=47324 msg="foo: bar.baz," value=30
      date=2020-03-30 time=16:29:24 ip=1.2.3.6 country="Korea, Republic of" garply"  id=47448 msg="foo: bar.baz," value=60
      

      【讨论】:

        【解决方案3】:

        你可以试试这样的:

        awk -F " " '{ $3=""; $4=""; $5="";  print}' file
        

        您基本上是将列设置为空字符串。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-11-20
          • 1970-01-01
          • 1970-01-01
          • 2016-05-11
          • 1970-01-01
          • 1970-01-01
          • 2017-06-19
          • 1970-01-01
          相关资源
          最近更新 更多