How to insert strings containing slashes with sed?

sed
afaf12 picture afaf12 · May 28, 2013 · Viewed 193.1k times · Source

I have a Visual Studio project, which is developed locally. Code files have to be deployed to a remote server. The only problem are the URLs they contain, which are hard-coded.

The project contains URLS such as ?page=one. For the link to be valid on the server, it must be /page/one .

I've decided to replace all URLS in my code files with sed before deployment, but I'm stuck on slashes.

I know this is a not a pretty solution, but it's simple and would save me a lot of time. The total number of strings I have to replace is fewer than 10. Total number of files which have to be checked is ~30.

Example describing my situation is below:

Command I'm using:

sed -f replace.txt < a.txt > b.txt

replace.txt which contains all the strings:

s/?page=one&/pageone/g
s/?page=two&/pagetwo/g
s/?page=three&/pagethree/g

a.txt:

?page=one&
?page=two&
?page=three&

Content of b.txt after I run my sed command:

pageone
pagetwo
pagethree

What I want b.txt to contain:

/page/one
/page/two
/page/three

Answer

lurker picture lurker · May 28, 2013

The easiest way would be to use a different delimiter in your search/replace lines, e.g.:

s:?page=one&:pageone:g

You can use any character as a delimiter that's not part of either string. Or, you could escape it with a backslash:

s/\//foo/

Which would replace / with foo. You'd want to use the escaped backslash in cases where you don't know what characters might occur in the replacement strings (if they are shell variables, for example).