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'
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'
Just use double quotes on the outside of the sed command.
It works with files too.
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.
The best way is to use
$'some string with \' quotes \''
eg:
This is kind of absurd but I couldn't get
\'
insed 's/ones/one\'s/'
to work. I was looking this up to make a shell script that will automatically addimport 'hammerjs';
to mysrc/main.ts
file with Angular.What I did get to work is this:
So for the example above, it would be:
I have no idea why
\'
wouldn't work by itself, but there it is.Quote
sed
codes with double quotes:I don't like escaping codes with hundreds of backslashes – hurts my eyes. Usually I do in this way:
I know this is going to sound like a cop out but I could never get sed working when there were both single and double quotes in the string. To help any newbies like me that are having trouble, one option is to split up the string. I had to replace code in over 100 index.hmtl files. The strings had both single and double quotes so I just split up the string and replaced the first block with
<!--
and the second block with-->
. It made a mess of my index.html files but it worked.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'
There are 3 strings in the sed expression, which the shell then stitches together:
sed 's/ones/two'
\'
's/'
Hope that helps someone else!