escaping – How to escape single quote in sed?

From fragile to solid…

1. Using double-quotes to enclose sed script:

Simpliest way:

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

But using double-quote lead to shell variables expansion and backslashes to be considered as shell escape before running sed.

1.1. Specific case without space or special chars

In this specific case, you could avoid enclosing at shell level:

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

will work until whole sedscript don’t contain spaces, semicolons, special characters and so on… (fragile!)

2. Using octal or hexadecimal representation:

This way is simple and efficient, if not as readable as next one.

sed 's/ones/oneo047s/' <<< 'ones thing'

sed 's/ones/onex27s/' <<< 'ones thing'

And as following character (s) is not a digit, you coul write octal with only 2 digits:

sed 's/ones/oneo47s/' <<< 'ones thing'

3. Creating a dedicated sed script

First ensure correct path to sed tool:

which sed
/bin/sed

Then adapt shebang in following:

cat <<"eosedscript" >sampleSedWithQuotes.sed
#!/bin/sed -f

s/ones/one's/;
eosedscript
chmod +x sampleSedWithQuotes.sed

From there, you could run:

./sampleSedWithQuotes.sed <<<'ones thing'
one's thing

This is the strongest and simpliest solution as your script is the most readable: cat sampleSedWithQuotes.sed

#!/bin/sed -f

s/ones/one's/;