Thursday, March 18, 2010

Using sed to Escape Quotes

Using sed to escape quotes in a piped in value:
$ echo "\"hello\"" | sed s/\"/\\\\\\\"/g
But backticks make it more interesting. Setting result of that into variable, via backticks:
$ resp=`echo "\"hello\"" | sed s/\"/\\\\\\\\\"/g`; echo $resp
Just for kicks, backticks within backticks (see Escaping Backticks Within Backticks):
$ resp2=`resp1=\`echo "\"hello\"" | sed s/\"/\\\\\\\\\\\\\\\\\"/g\`; echo $resp1`;echo $resp2
One more level of backticks:
$ resp3=`resp2=\`resp1=\\\`echo "\"hello\"" | sed s/\"/\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\"/g\\\`; echo $resp1\`;echo $resp2`;echo $resp3
And another:
$ resp4=`resp3=\`resp2=\\\`resp1=\\\\\\\`echo "\"hello\"" | sed s/\"/\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\"/g\\\\\\\`; echo $resp1\\\`;echo $resp2\`;echo $resp3`;echo $resp4
(Note: it can seem forgiving at times on the number of backticks if you have a few too many.)

So, the number of backslashes required for the escaped slash replacement value is 7 if not within backticks. However, for each level of backticks, it requires 9,17,33,65,etc. backslashes.

No comments: