The problem is that the shell expands $SERVER
before sed
ever sees it, and $SERVER
has slashes in it. So sed
gets this substitution command:
s/http:\/\/localhost:3010/http://example.com/g
... which has extra unquoted /
s and so is a syntax error.
You can use a different delimiter (whatever you put after the s
is what it will look for in the rest of the expression), as long as you can pick one you know won't show up in the value of $SERVER
. Then you don't need to quote any slashes at all:
sed -i "s^http://localhost:3010^$SERVER^g"
If you're using certain modern shells like bash
or zsh
, you can use a special parameter substitution to quote the slashes when SERVER
is expanded, which has the advantage of working no matter what characters are contained in the string:
sed -i "s/http:\/\/localhost:3010/${SERVER//\//\\\/}/g"
The general structure is ${varname//old/new}
to expand to the value of the variable $varname
with all¹ occurrences of the string old
replaced with the string new
. Unlike the case with sed
, there's no way to pick an alternate delimiter for this special parameter expansion, so the slashes and backslashes in our old and new strings have to be quoted with backslashes. That results in the leaning-toothpick effect; somewhat ugly, but effective.
¹ Using a single slash after the variable name will result in only the first occurrence of the old
string being replaced.