How do I escape double and single quotes in sed?

2019-01-13 12:13发布

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?

8条回答
疯言疯语
2楼-- · 2019-01-13 12:27

It's hard to escape a single quote within single quotes. Try this:

sed "s@['\"]http://www.\([^.]\+).com['\"]@URL_\U\1@g" 

Example:

$ sed "s@['\"]http://www.\([^.]\+\).com['\"]@URL_\U\1@g" <<END
this is "http://www.fubar.com" and 'http://www.example.com' here
END

produces

this is URL_FUBAR and URL_EXAMPLE here
查看更多
霸刀☆藐视天下
3楼-- · 2019-01-13 12:29
Prompt% cat t1
This is "Unix"
This is "Unix sed"
Prompt% sed -i 's/\"Unix\"/\"Linux\"/g' t1
Prompt% sed -i 's/\"Unix sed\"/\"Linux SED\"/g' t1
Prompt% cat t1
This is "Linux"
This is "Linux SED"
Prompt%
查看更多
叛逆
4楼-- · 2019-01-13 12:30

You need to use \" for escaping " character (\ escape the following character

sed -i 's/\"http://www.fubar.com\"/URL_FUBAR/g'
查看更多
smile是对你的礼貌
5楼-- · 2019-01-13 12:31

May be the "\" char, try this one:

sed 's/\"http:\/\/www.fubar.com\"/URL_FUBAR/g'
查看更多
干净又极端
6楼-- · 2019-01-13 12:40

My problem was that I needed to have the "" outside the expression since I have a dynamic variable inside the sed expression itself. So than the actual solution is that one from lenn jackman that you replace the " inside the sed regex with [\"].

So my complete bash is:

RELEASE_VERSION="0.6.6"

sed -i -e "s#value=[\"]trunk[\"]#value=\"tags/$RELEASE_VERSION\"#g" myfile.xml

Here is:

# is the sed separator

[\"] = " in regex

value = \"tags/$RELEASE_VERSION\" = my replacement string, important it has just the \" for the quotes

查看更多
趁早两清
7楼-- · 2019-01-13 12:43

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

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 dots and not as the regular expression pattern . which matches any one character.

查看更多
登录 后发表回答