使用sed在shell脚本中用反斜杠替换一行

时间:2015-06-15 12:20:29

标签: regex bash shell ssh sed

我正在尝试用文件中的sed替换这两行中的下一行。

    <rule>out_prefix=orderid ^1\\d\+ updatemtnotif/</rule>\n\
    <rule>out_prefix=orderid ^2\\d\+ updatemtnotif/</rule>\n\

以下命令似乎在bash提示符下作为命令执行时执行此操作

sed -i 's@out_prefix=orderid ^2\\\\d\\+ updatemtnotif/@out_prefix=orderid ^2\\\\d\\+ updatemtnotif_fr/@g' /opt/temp/rules.txt

但是,当我尝试使用此文档通过ssh远程执行相同的命令时,该命令无法修改该文件。 我认为这可能是一个逃避问题,但我没有运气试图以多种方式修改命令。任何人都可以告诉我应该怎么做才能让它在ssh上工作?提前谢谢!

澄清,

input: <rule>out_prefix=orderid ^2\\d\+ updatemtnotif/</rule>\n\
output: <rule>out_prefix=orderid ^2\\d\+ updatemtnotif_fr/</rule>\n\

2 个答案:

答案 0 :(得分:1)

您可以将其与ssh和heredoc一起使用,如下所示:

ssh -t -t user@localhost<<'EOF'
sed 's~out_prefix=orderid ^2\\\\d\\+ updatemtnotif/~out_prefix=orderid ^2\\\\d\\+ updatemtnotif_fr/~' ~/path/to/file
exit
EOF

PS:如图所示,引用 'EOF'非常重要。

答案 1 :(得分:0)

我设法解决了这个问题。我必须在shell脚本中使用的命令中转义反斜杠。

 's@out_prefix=orderid ^2\\\\\\\\d\\\\+ updatemtnotif/@out_prefix=orderid ^2\\\\\\\\d\\\\+ updatemtnotif_fr/@g' /opt/temp/rules.txt

这有很多反斜杠,但它确实可以解决问题。

相关问题