Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to escape single quote in sed?

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'
like image 924
Thomas Bratt Avatar asked Jul 01 '14 11:07

Thomas Bratt


People also ask

How do you escape a single quote?

Single quotes need to be escaped by backslash in single-quoted strings, and double quotes in double-quoted strings.

How do I escape a single quote in Linux?

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.

Can sed use double quotes?

@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.


3 Answers

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
like image 74
Kent Avatar answered Oct 07 '22 12:10

Kent


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!

like image 53
Thomas Bratt Avatar answered Oct 07 '22 12:10

Thomas Bratt


The best way is to use $'some string with \' quotes \''

eg:

sed $'s/ones/two\'s/' <<< 'ones thing'
like image 8
John C Avatar answered Oct 07 '22 12:10

John C