How do I escape double and single quotes in sed?

KRB picture KRB · Sep 22, 2011 · Viewed 147.1k times · Source

From what I can find, when you use single quotes everything inside is considered literal. I want that for my substitution. But I also want to find a string that has single or double quotes.

For example,

sed -i 's/"http://www.fubar.com"/URL_FUBAR/g'

I want to replace "http://www.fubar.com" with URL_FUBAR. How is sed supposed to recognize my // or my double quotes?

Thanks for any help!

EDIT: Could I use s/\"http\:\/\/www\.fubar\.\com\"/URL_FUBAR/g ?

Does \ actually escape chars inside the single quotes?

Answer

Kusalananda picture Kusalananda · Sep 22, 2011

The s/// command in sed allows you to use other characters instead of / as the delimiter, as in

sed 's#"http://www\.fubar\.com"#URL_FUBAR#g'

or

sed 's,"http://www\.fubar\.com",URL_FUBAR,g'

The double quotes are not a problem. For matching single quotes, switch the two types of quotes around. Note that a single quoted string may not contain single quotes (not even escaped ones).

The dots need to be escaped if sed is to interpret them as literal dots and not as the regular expression pattern . which matches any one character.