0

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?

Micheal Perr
  • 1,805
  • 5
  • 18
  • 24

2 Answers2

2

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.

Art Swri
  • 2,799
  • 3
  • 25
  • 36
0

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)

Community
  • 1
  • 1
glenn jackman
  • 238,783
  • 38
  • 220
  • 352