【问题标题】:Sed command : replacing a section in text file (bash)Sed 命令:替换文本文件中的一个部分 (bash)
【发布时间】:2018-05-24 06:21:46
【问题描述】:

我想将输入文件中的 section1 替换为临时文件中的 section1

我的inputfile 包含

section1
a1
section2
a2
section3
a1

这里是temporaryfile的内容:

section1
a1,b2

我目前的尝试是这样的:

 sed -i "/$section/,//{/$section/{p;r $temporaryfile};//p;d}"  $Inputfile

我希望看到以下输出:

section1
a1,b2
section2
a2
section3
a1

但是,我的代码只是给了我一条错误消息:

sed: -e expression #1, char 0: unmatched `{'
sed: -e expression #1, char 0: unmatched `{'

推荐https://superuser.com/questions/440013/how-to-replace-part-of-a-text-file-between-markers-with-another-text-file

【问题讨论】:

    标签: bash text sed


    【解决方案1】:

    sed 用于 s/old/new,仅此而已。对于其他任何事情,只需使用 awk 来实现简单性、稳健性、可移植性、效率等...:

    $ cat tst.awk
    NR%2 { name = $0; next }
    NR==FNR { val[name] = $0; next }
    { print name ORS (name in val? val[name] : $0) }
    
    $ awk -f tst.awk temporaryfile Inputfile
    section1
    a1,b2
    section2
    a2
    section3
    a1
    

    【讨论】:

      【解决方案2】:

      许多sed 方言要求大括号是单独的“命令”。所以你需要在最后的右大括号前加一个分号。

      另外,r 之后的参数没有任何引用,因此您需要明确终止它,例如换行。

      最后,作为一个小的优化,无操作空正则表达式// 没有任何用途;你可以忽略它。

      sed "/$section/,//{/$section/{p;r $temporaryfile
      };p;d;}"
      

      一些 shell 初学者对你可以在引号内换行感到惊讶,但这实际上是完全正常的。

      【讨论】:

        猜你喜欢
        • 2010-11-29
        • 2017-08-23
        • 1970-01-01
        • 2016-03-07
        • 2014-12-28
        • 2022-01-26
        • 1970-01-01
        • 1970-01-01
        • 2013-09-25
        相关资源
        最近更新 更多