【问题标题】:How do I insert a newline/linebreak after a line using sed如何使用 sed 在一行之后插入换行符/换行符
【发布时间】:2013-06-26 03:04:21
【问题描述】:

我花了一段时间才弄清楚如何做到这一点,所以发布以防其他人也在寻找相同的东西。

【问题讨论】:

标签: bash shell sed zsh


【解决方案1】:

最简单的选择 -->

sed 'i\

'文件名

【讨论】:

    【解决方案2】:

    另一种可能性,例如如果您没有空的保持寄存器,可能是:

    sed '/pattern/{p;s/.*//}' file
    

    说明:
    /pattern/{...} = 应用命令序列,如果找到符合模式的行,
    p = 打印当前行,; = 命令之间的分隔符,
    s/.*// = 替换模式寄存器中的任何内容,
    然后自动将空模式寄存器打印为附加行)

    【讨论】:

      【解决方案3】:
      sed '/pattern/a\\r' file name 
      

      它会在模式之后添加一个返回,而g 会用一个空行替换模式。

      如果必须在文件末尾添加新行(空白),请使用:

      sed '$a\\r' file name
      

      【讨论】:

      • 回车与换行:有些人需要使用\n 而不是\r
      【解决方案4】:

      简单的替换效果很好:

      sed 's/pattern.*$/&\n/'
      

      例子:

      $ printf "Hi\nBye\n" | sed 's/H.*$/&\nJohn/'
      Hi
      John
      Bye
      

      为了符合标准,将 \n 替换为反斜杠换行符:

      $ printf "Hi\nBye\n" | sed 's/H.*$/&\
      > John/'
      Hi
      John
      Bye
      

      【讨论】:

      • 要回答所提出的问题,您必须执行sed 's/pattern.*/&\n/',否则您将在匹配之后插入换行符,而不是在行尾。另请注意,您的解决方案需要 GNU sed(不适用于 BSD/OSX,因为 BSD sed 实现不支持 替换字符串中的转义序列 \n )。
      • 哦,谢谢,我不知道 GNU sed 和 BSD/OSX sed 之间的区别。值得知道!
      • ++;不幸的是,有很多不同之处; BSD Sed 只实现了对 POSIX 规范的一些扩展。而 GNU Sed 实现了更多——我试图编译 this answer 中的差异。
      【解决方案5】:

      对于在模式后添加换行符,您也可以说:

      sed '/pattern/{G;}' filename
      

      引用GNU sed manual:

      G
          Append a newline to the contents of the pattern space, and then append the contents of the hold space to that of the pattern space.
      

      编辑:

      顺便说一句,这恰好在sed one liners 中有所提及:

       # insert a blank line below every line which matches "regex"
       sed '/regex/G'
      

      【讨论】:

      • sed '/\n/G' filename 不起作用。但是sed '/e/G' filename 有效。
      【解决方案6】:

      这个 sed 命令:

      sed -i '' '/pid = run/ a\
      \
      ' file.txt
      

      使用以下命令查找行:pid = run

      file.txt 之前

      ; Note: the default prefix is /usr/local/var
      ; Default Value: none
      ;pid = run/php-fpm.pid
      
      ; Error log file
      

      并在 file.txt 中的该行之后添加一个换行符

      file.txt 之后

      ; Note: the default prefix is /usr/local/var
      ; Default Value: none
      ;pid = run/php-fpm.pid
      
      
      ; Error log file
      

      或者如果你想添加文本和换行符:

      sed -i '/pid = run/ a\
      new line of text\
      ' file.txt
      

      file.txt 之后

      ; Note: the default prefix is /usr/local/var
      ; Default Value: none
      ;pid = run/php-fpm.pid
      new line of text
      
      ; Error log file
      

      【讨论】:

      • sed 'a' 是个好主意...我会使用 sed -e '/pid = run/ s/$/\n/'sed -e '/pid = run/ s/$/\nnew line of text/'
      猜你喜欢
      • 1970-01-01
      • 2023-03-26
      • 2023-02-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多