【问题标题】:Using sed to insert lines with escaped search pattern使用 sed 插入带有转义搜索模式的行
【发布时间】:2016-02-12 00:28:01
【问题描述】:

我按照using sed to insert lines 的示例将其放入特定模式匹配位置的文件中。我已经在我的机器上运行了该问题的示例,它运行良好。

所以,对我来说,具体来说,我正在尝试插入以下内容:

<Location "someplace">
    AuthBasicProvider ldap
    AuthType Basic
    AuthName "Auth"
    AuthLDAPURL someurl
    AuthzLDAPAuthoritative on

    AuthLDAPBindDN someuser
    AuthLDAPBindPassword somepassword
</Location>

我想将它插入到 .conf 文件 (this one to be exact) 的末尾,特别是在关闭 &lt;/VirtualHost&gt; 之前。

但是,当我跑步时

sed -n 'H;${x;s/\<\/VirtualHost> .*\n/test string &/;p;}' vhost.conf

为了测试,文件的内容被打印出来但文件没有被改变。我是不是逃错了&lt;/VirtualHost&gt; 或者我错过了什么?

(我也愿意接受其他将我的内容放入文件的解决方案。)

【问题讨论】:

    标签: bash shell sed


    【解决方案1】:

    这适用于 GNU Sed:

    sed -i -n 'H;${x;s/<\/VirtualHost>.*/    test string\n&/;p;}' vhost.conf
    

    对于 OSX/BSD:

    sed -i '' -n 'H;${x;s/<\/VirtualHost>.*/    test string\'$'\n''&/;p;}' vhost.conf
    

    【讨论】:

    • 我需要从中学习很多东西(我正在使用 BSD)。谢谢!
    • 快速跟进问题:将我的大型多行内容​​从上方获取到此答案而不是 test string 的最佳方法是什么?我能想到几种方法,但都很难看。
    【解决方案2】:

    这可能对你有用(GNU sed):

    cat <<\! | sed -i '/<\/VirtualHost>/e cat /dev/stdin' file
    test string
    to be
    inserted
    !
    

    或者更容易:

    sed -i '/<\/VirtualHost>/i\
    test string\
    to be\
    inserted' file
    

    【讨论】:

      【解决方案3】:

      使用 -i 开关进行就地替换:

      sed -i -n 'H;${x;s/\<\/VirtualHost> .*\n/test string &/;p;}' vhost.conf
      

      【讨论】:

      • 运行该命令后,我在vhost.conf 文件中的任何位置都找不到字符串test string - 与上面的问题相同。
      • (另外,运行任一命令显然会创建另一个文件vhost.confn,但据我所知它与vhost.conf 相同)
      • 它是 sed -i -n(不是 -in)。这适用于 GNU sed。 BSD sed 要求您指定一个空白后缀,例如 -i ''
      猜你喜欢
      • 1970-01-01
      • 2012-07-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-04
      相关资源
      最近更新 更多