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

Viewed 152

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.

Example:

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

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:

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. I tried many escaping tricks like using \ or '"'"' but it still does not work. I will be happy to have some help and to learn more about bash, my studies in shell are far behind me :)

Thank you in advance!

zet

2 Answers

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 -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.

Perl's maybe more straightforward here, but really not a lot:

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

This might work for you (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 \\".

Related