Micheal Perr
Micheal Perr

Reputation: 1895

Replace a phrase in a file with a string which contains special Characters

I am using sed -e "s/foo/$bar/" -e "s/some/$text/" file.whatever to replace a phrase in a certain file. The problem is that the $bar string contains multiple special characters like /. So when I try to replace something in a text file using the following code...

#!/bin/bash

bar="http://stackoverflow.com/"

sed -e "s/foo/$bar/" -e "s/some/$text/ file.whatever

...then I get an error saying : sed: unknown option to s is there anything I can do about it?

Upvotes: 0

Views: 1364

Answers (2)

glenn jackman
glenn jackman

Reputation: 246817

You can get this difficulty in sed regardless of what delimiters you use, especially if you don't know what the string contains. I'd pick a different method for passing the shell variables into the helper interpreter.

awk -v rep1="$bar" -v rep2="$text" '{sub(/foo/, rep1); sub(/some/, rep2); print}'

or

perl -spe 's/foo/$rep1/; s/some/$rep2/' -- -rep1="$bar" -rep2="$text"

Correctness trumps brevity in this case.
(reference for Perl example)

Upvotes: 0

Art Swri
Art Swri

Reputation: 2804

You can use any delimiter. s@some@SOME@ for example. Another good delimiter is vertical-bar. Other chars can work but have special significance for some contexts such as regular expressions.

Upvotes: 2

Related Questions