【问题标题】:Sed command errorsed 命令错误
【发布时间】:2015-08-02 13:03:44
【问题描述】:

我在文件中有一行,想在它下面添加。 我一直在尝试使用命令

sed -e '/</session-config>/a\<security-constraint>\' -i filename

但它不起作用。错误是:

sed: -e expression #1, char 43: unterminated `s' command

示例输入文件

<more></more>
<session-config>20</session-config>
<otherfields>10</otherfields>

在 sed 命令之后

<more></more>
<session-config>20</session-config>
<security-constraint>
<otherfields>10</otherfields>

请帮忙。

谢谢。

【问题讨论】:

    标签: linux sed


    【解决方案1】:

    您需要转义&lt;/session-config&gt; 中的/。否则,它将被视为要匹配的正则表达式的结尾,然后s 是应用于这些行的命令的开头:

    sed -e '/<\/session-config>/a\<security-constraint>\' -i filename
    

    【讨论】:

      【解决方案2】:

      使用不同的分隔符。此外,一些 sed 需要在 a 之后换行。这应该有效:

      sed -e '\@<session-config>@a\
          <security-constraint>\'
      

      【讨论】:

      • posix 版本需要 a 之后的新行,而不是 GNU sed 版本(但在这种情况下,a 之后的 \ 将被忽略(a\n 产生 n on附加行之前没有空行)但我更喜欢你的版本在任何地方都可以
      【解决方案3】:

      使用另一个分隔符,您不需要反斜杠。
      你找到的字符串必须放回去,所以用 & 代替它。
      新行上的新字符串:我使用\n。当你的 sed 不支持它时, 使用真正的换行符。 当你想添加一行时,不要使用a,而是让它成为替换字符串的一部分。

      sed -e '#</session-config>#&\n<security-constraint>trust_nobody</security-constraint>#' -i filename
      

      【讨论】:

        【解决方案4】:

        为了清晰、简单、健壮性、可移植性和其他所有理想的软件质量,只需使用 awk:

        $ awk '{print} index($0,"</session-config>"){print "<security-constraint>"}' file
        <more></more>
        <session-config>20</session-config>
        <security-constraint>
        <otherfields>10</otherfields>
        

        请注意,上面的命令将您正在搜索的文本和您添加的文本都视为字符串,因此不在乎它们包含哪些字符(当然,以" 结尾的字符串除外)。以上将适用于所有操作系统中的所有现代 awk。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2017-12-21
          • 2016-11-17
          • 2013-01-28
          • 2012-05-05
          • 2019-07-22
          • 2014-07-22
          • 2017-04-14
          相关资源
          最近更新 更多