【问题标题】:insert a line using sed使用 sed 插入一行
【发布时间】:2017-03-10 13:34:49
【问题描述】:

我有一个类似的ini文件:

...
abc = 123
def = 456
...

我想将其更改为:

...
abc = 123
xyz = 987
def = 456
...

我没有成功地尝试过这个: sed -i 's/abc = 123\ndef = 456/abc = 123\nxyz = 987\ndef = 456/g' myfile.ini 如何修复我对 sed 的呼叫以使其正常工作?

【问题讨论】:

  • 你的搜索条件是什么...在abc = 123之后插入一行?在行前插入def = 456?还是仅在这两行彼此相邻时才插入?

标签: linux replace sed


【解决方案1】:

使用 sed 的另一种方法:

sed '/abc = 123/N;s/\ndef = 456/\nxyz = 987&/' myfile.ini

【讨论】:

    【解决方案2】:
    sed '
        /^def / {     # if this line matches the  2nd pattern
            x         # swap this line and the hold space
            /^abc / { # if this line matches the 1st pattern
                      # insert the new line
                i\
    xyz = 987
            }
            x         # re-swap this line and the hold space
        }
        h             # put this line into the hold space
    ' file.ini
    

    【讨论】:

      【解决方案3】:

      Sed 自然只查看一行,因此它不会找到您想要的'\n' 字符。最简单的解决方案是将所有 '\n' 替换为另一个临时字符,例如 '\f'(换页符)。

      这是我一直在使用的骇人听闻的方法。 (为清楚起见分开)

      cat myfile.ini |
      tr '\n' '\f' |
      sed -e "s/abc = 123\fdef = 456/abc = 123\fxyz = 987\fdef = 456/g" |
      tr '\f' '\n'
      

      '\f' 是换页符。如果您使用的是 MacOS,则需要将 sed 语句中的所有 '\f' 替换为 $(printf '\f')

      注意:我还建议使用 sed 分组语法以使您的模式更易于阅读。

      很难用 sed 进行多行编辑。您应该查看 perl 以获得更复杂的编辑。

      【讨论】:

      【解决方案4】:

      这是一种在模式后追加一行的可移植方式:

      <myfile.ini sed '/abc = 123/a\
      xyz = 789
      '
      

      输出:

      abc = 123
      xyz = 789
      def = 456
      

      【讨论】:

        猜你喜欢
        • 2023-03-26
        • 2023-02-06
        • 1970-01-01
        • 2011-09-26
        • 1970-01-01
        • 1970-01-01
        • 2013-03-11
        相关资源
        最近更新 更多