How to escape a single quote in a sed expression that is already surrounded by quotes?
For example:
sed 's/ones/one's/' <<< 'ones thing'
Single quotes need to be escaped by backslash in single-quoted strings, and double quotes in double-quoted strings.
A single quote is not used where there is already a quoted string. So you can overcome this issue by using a backslash following the single quote. Here the backslash and a quote are used in the “don't” word.
@DummyHead Here's another approach: if you use single quotes, the sed command is exactly as you type it. If you use double quotes, you must take into account all shell substitutions and elaborations to "visualize" what command is eventually passed on to sed.
Quote sed
codes with double quotes:
$ sed "s/ones/one's/"<<<"ones thing"
one's thing
I don't like escaping codes with hundreds of backslashes – hurts my eyes. Usually I do in this way:
$ sed 's/ones/one\x27s/'<<<"ones thing"
one's thing
One trick is to use shell string concatenation of adjacent strings and escape the embedded quote using shell escaping:
sed 's/ones/two'\''s/' <<< 'ones thing'
two's thing
There are 3 strings in the sed expression, which the shell then stitches together:
sed 's/ones/two'
\'
's/'
Hope that helps someone else!
The best way is to use $'some string with \' quotes \''
eg:
sed $'s/ones/two\'s/' <<< 'ones thing'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With