【问题标题】:add newline after specific lines with sed使用 sed 在特定行之后添加换行符
【发布时间】:2015-01-24 05:45:41
【问题描述】:

我的输出为:

A: this thing
B: that thing
A: 23
B: 46
A: negative
B: positive

我正在使用 sed/awk 创建。如何使用 sed(我认为 sed 是正确的选择?)在每个 B: 行之后添加换行符以产生:

A: this thing
B: that thing

A: 23
B: 46

A: negative
B: positive

【问题讨论】:

    标签: regex bash awk sed


    【解决方案1】:
    sed '/^B:/a\
        ' file
    

    a 命令在匹配行之后附加以下内容。

    您还可以执行's/^B:.*/&\n/' 之类的操作,编辑行并添加换行符。

    awk也很容易处理。

    【讨论】:

    • 谢谢。我想我最喜欢's/^B:.*/&\n/' 方法,但你能解释一下吗?我知道^B: 匹配以B: 开头的行,并假设.* 是通配符,但& 是做什么的?它只是说“我们在第一部分中询问的任何内容”吗?
    • 是的。 .* 匹配行的其余部分(因此是& 中匹配模式的一部分),因此换行符位于行尾而不是中间。
    【解决方案2】:

    使用 awk 你可以做到:

    awk '{print} /^B:/{print ""}' file
    A: this thing
    B: that thing
    
    A: 23
    B: 46
    
    A: negative
    B: positive
    

    【讨论】:

      【解决方案3】:

      使用GNU sed(使用G 选项将保持空间(默认为空白)附加到模式空间):

      sed '/^B:/G' file
      A: this thing
      B: that thing
      
      A: 23
      B: 46
      
      A: negative
      B: positive
      

      【讨论】:

        【解决方案4】:

        一种使用sed的方式...

        sed 's/^\(B:.*\)/\1\n/'
        

        或如@JonathanLeffler 评论如下:

        sed 's/^B:.*/&\n/'
        

        【讨论】:

        • 或者,更简单,s/^B: .*/&\n/,不需要显式捕获。
        【解决方案5】:

        试试这样的:

        sed -E -i 's:(^B.*$):\1\n:g' filename
        

        它在filename 中以字母 B 开头的每一行追加一个新行。

        【讨论】:

        • 或者,更简单,s/^B: .*/&\n/,不需要显式捕获。
        【解决方案6】:

        这是另一个awk

        awk '/^B:/ {$0=$0"\n"} 1' file
        A: this thing
        B: that thing
        
        A: 23
        B: 46
        
        A: negative
        B: positive
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2013-06-26
          • 1970-01-01
          • 1970-01-01
          • 2013-04-18
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多