【问题标题】:How to add line with spaces at beginning, and with backslash at end with sed?如何在开头添加空格,并在结尾添加反斜杠与sed?
【发布时间】:2014-11-05 14:01:51
【问题描述】:

我知道在文件中在另一行之后添加一行的 sed 语法,即

sed -i '/LINE1/a LINE2' FILE

这会在 FILE 中的 LINE1 之后添加 LINE2 对吗?如何在末尾添加带有反斜杠的行?例如,来自

This is a a line \
    Indented line1 \
    Indented line2 \
    Line3

This is a a line \
    Indented line1 \
    Indented line2 \
    Added line \
    Line3

【问题讨论】:

    标签: bash awk sed


    【解决方案1】:

    只需将反斜杠放入并转义即可:

    sed -i '/line2/a Added line \\' FILE
    

    如果你想要四个空格的缩进,那么:

    sed -i '/line2/a \    Added line \\' FILE
    

    【讨论】:

      【解决方案2】:

      只需使用 awk,sed 最适合单行上的简单替换,而不是涉及多行的任何事情或任何其他远程复杂的事情:

      $ awk '{print} /line2/{ print substr($0,1,match($0,/[^[:space:]]/)-1) "Added line \\" }' file
      This is a a line \
          Indented line1 \
          Indented line2 \
          Added line \
          Line3
      

      无论您的前导空格是什么,上面都会将您添加的行与前一行的缩进对齐,因为它只是用替换文本替换空格之后的任何内容。

      【讨论】:

      【解决方案3】:

      你可以使用插入命令:

      sed '/\\$/!i \    Added line \\' file
      

      【讨论】:

        【解决方案4】:

        这对你有用吗?

        awk 'NR==3{$0=$0 "\n\tAdded Line \\"}7' file
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2015-01-16
          • 2019-12-11
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-11-18
          • 2012-08-03
          相关资源
          最近更新 更多