【问题标题】:Sed special characterssed 特殊字符
【发布时间】:2018-01-11 06:27:29
【问题描述】:

我想更改某些文件中的主目录。 我想我必须避开大括号 - 像这样:

sed -i 's/\$\{HOME\}/\/casper\/home/g' /var/tmp/casper.txt

我在 sed 中所经历的一切都告诉我,我必须避开括号,但我没有。我唯一需要逃避的是美元符号。 sed 使用什么样的正则表达式引擎,需要转义的特殊字符列表在哪里,不需要转义的特殊字符列表在哪里。

sed -i 's/\${HOME}/\/casper\/home/g' /var/tmp/casper.txt

【问题讨论】:

    标签: sed


    【解决方案1】:

    我不是专家,只是一个正则表达式的用户,所以我不能给你严格的技术答案,但根据info sed,如果在没有-r--regexp-extended)的情况下调用,它会使用基本的正则表达式。如果输入了-r,则使用扩展的正则表达式。 info的附录中有说明:

    The only difference between basic and extended regular expressions is in
    the behavior of a few characters: '?', '+', parentheses, braces ('{}'),
    and '|'.  While basic regular expressions require these to be escaped if
    you want them to behave as special characters, when using extended
    regular expressions you must escape them if you want them _to match a
    literal character_.
    

    顺便说一句,如果您需要在 sed 的正则表达式中添加一个斜线,使用不同的符号作为分隔符非常有用。它不需要是斜线,你可以选择任意符号,例如它可以是@。所以改为:

    sed -i 's/\${HOME}/\/casper\/home/g' /var/tmp/casper.txt
    

    你可以这样做:

    sed -i 's@\${HOME}@/casper/home@g' /var/tmp/casper.txt
    

    【讨论】:

      猜你喜欢
      • 2011-05-17
      • 2014-09-13
      • 1970-01-01
      • 2019-09-07
      • 2021-06-11
      • 2018-11-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多