简体   繁体   English

如何使用 args 和 echo 命令在 sed 命令中转义双引号?

[英]How can I escape double quotes in sed command using args and echo command?

I am working on a bash script, trying to find a regexp in a file, substitute (with sed) a part of regexp corresponding to a float number by this number divided by 2.我正在研究 bash 脚本,试图在文件中找到一个正则表达式,用这个数字除以 2 替换(使用 sed)对应于浮点数的正则表达式的一部分。

Example:例子:

echo set NEX \"2.00\" > testfile
cat testfile

Output: Output:

set NEX "2.00"

Command:命令:

sed -i -r 's/(set NEX ")([0-9.]+)(")/echo \1$(echo "scale=2;\2\/2" | bc)\3/e' testfile
cat testfile

Output: Output:

set NEX 1.00

So, my problem is that echo in sed command seems not to escape and interpret the double quote returned by \1 and \3.所以,我的问题是 sed 命令中的 echo 似乎没有转义和解释 \1 和 \3 返回的双引号。 I tried many escaping tricks like using \ or '"'"' but it still does not work.我尝试了许多 escaping 技巧,例如使用 \ 或 '"'"' 但它仍然不起作用。 I will be happy to have some help and to learn more about bash, my studies in shell are far behind me:)我很乐意得到一些帮助并了解有关 bash 的更多信息,我在 shell 的学习远远落后于我:)

Thank you in advance!先感谢您!

zet泽特

Because the sed e command calls the shell, which interprets away quotes, it's easiest to simply replace the quotes in a subsequent sed command:因为 sed e命令调用 shell,它会解释掉引号,所以最简单的方法是简单地替换后续 sed 命令中的引号:

sed -r '/set NEX/{s/(set NEX ")([0-9.]+)(")/echo \1$(echo "scale=2;\2\/2" | bc)\3/e;s/\b[0-9.]+\b/"&"/}' testfile

Above adds /set NEX/{} around your command and then adds s/\b[0-9.]+\b/"&"/ after it to enclose the float in double quotes.上面在您的命令周围添加/set NEX/{} ,然后在其后添加s/\b[0-9.]+\b/"&"/以将浮点数括在双引号中。

Perl's maybe more straightforward here, but really not a lot: Perl 在这里可能更直接,但实际上不是很多:

perl -pe 's#\b([.0-9]+)\b#sprintf "%3.2f",$1/2.0#e if /set NEX/' testfile

Perl doesn't lose the double quotes, and is only modifying the float in the s###e Perl 不会丢失双引号,只是修改s###e中的浮点数

This might work for you (GNU sed):这可能对您有用(GNU sed):

sed -E 's/(set Nex)"([0-9]+)"/echo \1\\"$(echo "scale=2;\2\/2"|bc)\\"/e' file

For the " 's to be literal when echoed they must be escaped \" 's.为了使"的在回显时是字面的,它们必须被转义\" Then the escapes must be escaped for the evaluation of the echo command by the e flag of the substitution \\" .然后必须转义转义,以便通过替换\\"e标志评估 echo 命令。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM