【问题标题】:sed delete lines between two patterns, without the second pattern, including the first patternsed 删除两个模式之间的行,没有第二个模式,包括第一个模式
【发布时间】:2017-03-21 18:25:55
【问题描述】:

我的输入文件如下所示:

[1234]
text 
text
text

[3456]
text 
text
text

[7458]
text 
text
text

我想删除模式之间的所有行,包括 FROM_HERE 和不包括 TO_HERE。

sed '/FROM_HERE/,/TO_HERE/{//p;d;}'

现在我有:

sed '/^\['"3456"'\]/,/^\[.*\]/{//p;d;}'

但此命令也不会删除 FROM_HERE 行。最后的 3456 输入文件应如下所示:

[1234]
text 
text
text

[7458]
text 
text
text

我怎样才能做到这一点?谢谢。

【问题讨论】:

标签: design-patterns sed


【解决方案1】:

您可以从模式中删除行到下一个空白行:

sed '/^\['"3456"'\]/,/^$/{d;}' file

【讨论】:

    【解决方案2】:

    注意:为了示例,我将只匹配 3456 和 7458(而不是“完全 [3456]”)

    你可以这样做:

    ~$ cat t
    [1234]
    text1
    text1
    text1
    
    [3456]
    text2
    text2
    text2
    
    [7458]
    text3
    text3
    text3
    
    ~$ sed '/3456/,/7458/{/7458/!d}' t
    [1234]
    text1
    text1
    text1
    
    [7458]
    text3
    text3
    text3
    

    即:在 FROM_HERE 和 TO_HERE (/3456/,/7458/) 之间执行以下操作:如果与 TO_HERE ({/7458/!d}) 不匹配则删除

    【讨论】:

      【解决方案3】:

      要删除从模式[3456] 开始直到遇到模式[7458] 的行(不包括以模式结尾的行),请使用以下命令:

      sed '/^\[3456\]/,/\[7458\]/{/\[7458\]/b;d;}' testfile
      

      /\[7458\]/b - 这里的b命令用于跳过包含\[7458\]模式的行

      d命令是删除一行 输出:

      [1234]
      text 
      text
      text
      
      [7458]
      text 
      text
      text
      

      https://www.gnu.org/software/sed/manual/sed.html#Branching-and-flow-control

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-02-10
        • 1970-01-01
        • 1970-01-01
        • 2021-10-15
        • 2015-05-07
        相关资源
        最近更新 更多