How to escape single quote in 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'

Just use double quotes on the outside of the sed command.

$ sed "s/ones/one's/" <<< 'ones thing'
one's thing

It works with files too.

$ echo 'ones thing' > testfile
$ sed -i "s/ones/one's/" testfile
$ cat testfile
one's thing

If you have single and double quotes inside the string, that's ok too. Just escape the double quotes.

For example, this file contains a string with both single and double quotes. I'll use sed to add a single quote and remove some double quotes.

$ cat testfile
"it's more than ones thing"
$ sed -i "s/\"it's more than ones thing\"/it's more than one's thing/" testfile 
$ cat testfile 
it's more than one's thing

This is kind of absurd but I couldn't get \' in sed 's/ones/one\'s/' to work. I was looking this up to make a shell script that will automatically add import 'hammerjs'; to my src/main.ts file with Angular.

What I did get to work is this:

apost=\'
sed -i '' '/environments/a\
import '$apost'hammerjs'$apost';' src/main.ts

So for the example above, it would be:

apost=\'
sed 's/ones/one'$apost's/'

I have no idea why \' wouldn't work by itself, but there it is.