Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I escape double and single quotes in sed?

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?

like image 202
KRB Avatar asked Sep 22 '11 15:09

KRB


People also ask

Does sed work with double quotes?

Single quotes tell shell to not perform any expansion at all and sed gets three arguments -n , /sweet/,$p , and file . When using double quotes, variables get expanded. Presuming variable=sweet and p not being set, second sed call got the following three arguments: -n , /sweet/, , and file .

How do you escape a single quote in a double quote?

No escaping is used with single quotes. Use a double backslash as the escape character for backslash.

How do you escape quotation marks?

Alternatively, you can use a backslash \ to escape the quotation marks.


1 Answers

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.

like image 71
Kusalananda Avatar answered Oct 07 '22 06:10

Kusalananda