代码之家  ›  专栏  ›  技术社区  ›  gazzwi86

Mac OS X上的SED

  •  1
  • gazzwi86  · 技术社区  · 13 年前

    所以我试着通过macports安装gsed,但这并没有解决问题。我本来打算卸载它以减少混乱,然而,在我这么做之前,我该如何修复下面的错误。据我所知,这是因为sed Mac OS X的BSD版本正在运行,但我发现的修复程序似乎都没有帮助。

    sed: 1: "/\[staging: production\ ...": command i expects \ followed by text
    
    #!/bin/bash
    
    test="lala\nkjdsh"
    sed -i -e '/\[staging: production\]/ i '$test'' ./test.txt
    
    2 回复  |  直到 13 年前
        1
  •  1
  •   Igor Chubin    13 年前

    您出现此问题是因为 $test 。尝试删除 \n 从它。

    POSIX标准 sed 只接受 \n个 作为搜索模式的一部分。OS X使用FreeBSD 标准化的 ,严格遵守POSIX

    因此,如果您需要在变量中使用换行符,则需要编写以下内容:

    $ test="lala\
    > kjdsh"
    

    您还可以使用perl解决该任务:

    $ test="lala\nkjdsh"
    $ perl -n -i -e 'print "'"$test"'\n" if /\[staging: production\]/; print;' ./test.txt
    

    示例:

    $ echo '[staging: production]' > /tmp/test.txt
    $ test="lala\nkjdsh"
    $ perl -n -i -e 'print "'"$test"'\n" if /\[staging: production\]/; print;' ./test.txt
    $ cat ./test.txt
    lala
    kjdsh
    [staging: production]
    
        2
  •  1
  •   geirha    13 年前

    如果测试变量不包含仅包含 . 你可以使用 ed 要编辑文件:

    printf '%s\n' '/\[staging: production\]/i' "$test" . w | ed -s ./test.txt
    

    看见 http://wiki.bash-hackers.org/howto/edit-ed 了解更多关于 教育部

    编辑:哦,我错过了你的变量中实际上有反斜杠-后面的N,而不是字面上的换行符。如果您使用文字换行符,则以上内容应该有效。

    编辑2:考虑到评论中给出的粘贴框,请尝试:

    #!/usr/bin/env bash
    #...
    ed -s ./test.txt << EOF
    /\[staging: production\]/i
    
    ; some comment
    someStuffHere[] = "XYZ"
    someMoreStuff[] = "$someShellVar"
    
    ; another comment
    .
    w
    EOF
    

    这个 单独在一条线上结束 i nsert命令,以及 w 是写命令,它实际上将更改保存到文件中(例如 :w 在vim中)