How to insert strings containing slashes with sed? [duplicate] Ask Question

How to insert strings containing slashes with sed? [duplicate] Ask Question

I have a Visual Studio project, which is developed locally. Code files have to be deployed to a remote server. The only problem is 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 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. A total number of files which have to be checked is ~30.

An example describing my situation is below:

The 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

ベストアンサー1

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).

おすすめ記事