【问题标题】:How to remove next line if next line matching pattern with sed?如果下一行与 sed 匹配模式,如何删除下一行?
【发布时间】:2019-09-27 20:49:41
【问题描述】:

如果下一行与模式匹配,我将无法删除下一行。 例如:

define service{
host_name               A
notification_period     F
}


define service{
host_name               A
notification_period     metrologie
notification_period     F
}

我检查模式计量。如果下一行包含notification_period,我想删除行notification_period F。

我尝试使用命令 sed '/metrologie/{h;d;};/notification_period/{x;!d;}' $file

但它将字符串转换为:

define service{
host_name               A

}


define service{
host_name               A
notification_period     metrologie
}

我想要这个输出:

define service{
host_name               A
notification_period     F
}


define service{
host_name               A
notification_period     metrologie
}

【问题讨论】:

    标签: sed


    【解决方案1】:

    你可以使用

    sed '/metrologie/{N;/\n.*notification_period/{s/\n.*//}}' file
    

    请参阅online sed demo

    详情

    • /metrologie/ - 找到带有metrologie 的行 接着
      • N; - 读取模式空间的下一行,并在其前添加换行符
      • /\n.*notification_period/ - 尝试将模式空间中的当前文本与模式匹配换行符、任何 0+ 字符、notification_period 匹配
      • {s/\n.*//}} - 如果上述模式匹配,则将换行符及其后面的所有内容替换为空字符串。

    【讨论】:

      【解决方案2】:

      这可能对你有用(GNU sed):

      sed ':a;/metrologie/{n;/notification_period/d;ba}' file
      

      如果一行包含metrologie,则打印并获取下一行。如果该行包含notification_period,则将其删除,否则重复。

      【讨论】:

      • 所以,我的解决方案的不同之处在于,metrologie 包含notification_period 的行下面的所有行都被删除了,对吧?
      • @WiktorStribiżew 不,不同之处在于如果metrologie 下方的行不包含notification_period,则不会忘记该行,但会测试它是否也包含metrologie。在您的解决方案中,如果条件为真,则删除该行,但如果为假,则不再测试。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-10-26
      • 2017-12-06
      • 1970-01-01
      • 2018-08-08
      • 2022-01-14
      • 2016-12-17
      • 1970-01-01
      相关资源
      最近更新 更多