VaTo
VaTo

Reputation: 3098

How can I escape / and " in my sed command?

I'm trying to search and replace every occurrence of

 <a href="#" data-role="button" data-inline="true" data-rel="back">Cancel</a>

with:

<a data-role="button" data-inline="true" onclick="$(this).closest('[data-role=popup]').popup('close');">Cancel</a>

So I use sed for this purpose, the problem is that in my search and replace string it contains / and " which I don't know if I should escape them or not so I don't get errors. Any suggestions?

find . -type f -print0 | xargs -0 sed -i 's/<a href="#" data-role="button" data-inline="true" data-rel="back">Cancel</a>/<a data-role="button" data-inline="true" onclick="$(this).closest('[data-role=popup]').popup('close');">Cancel</a>/g'

Upvotes: 1

Views: 153

Answers (2)

Gary_W
Gary_W

Reputation: 10360

You do not have to use the slash as the sed delimiter. It will use whatever character is after the 's'. Make it one that is not in your data and you will not have to worry about escaping the slashes in the data. Don't worry about the double-quotes:

$ cat x
gand"alf     :0           2015-05-19 14:47 (:0)
gandalf     pts/1        2015-05-27 09:49 (:0)
$ sed 's!pts/1!efs/1!g' x
gand"alf     :0           2015-05-19 14:47 (:0)
gandalf     efs/1        2015-05-27 09:49 (:0)
$ sed 's!gand"alf!efs/1!g' x
efs/1     :0           2015-05-19 14:47 (:0)
gandalf     pts/1        2015-05-27 09:49 (:0)
$ 

Upvotes: 1

Marcus Stemple
Marcus Stemple

Reputation: 120

This answer on a SE network site might be helpful: https://unix.stackexchange.com/questions/32907/what-characters-do-i-need-to-escape-when-using-sed-in-a-sh-script

Essentially, it says that:

you need a backslash before / if it is to appear in the regex.

Other resources I have found have also confirmed this, so I'd give it a try.

The answer doesn't say anything about double quotes, and from what I've found elsewhere, those don't appear to be a problem in sed, so don't worry about escaping those.

Upvotes: 0

Related Questions