1

I have some js files in which I want to replace http://localhost:3010 with environment variable $SERVER

e.g. the $SERVER=http://example.com

A sample file is server=http://localhost:3010 it should be this server=http://example.com after replacement

I tried following find . -type f -name "*.js" -exec sed -i "s/http:\/\/localhost:3010/$SERVER/g" {} +

find . -type f -name "*.js" -exec sed -i 's/http:\/\/localhost:3010/$SERVER/g' {} +

Both does not work

anubhava
  • 761,203
  • 64
  • 569
  • 643
AhmedRana
  • 486
  • 9
  • 22

2 Answers2

2

You may try this:

find . -type f -name "*.js" -exec sed -i "s~http://localhost:3010~$SERVER~g" {} +

So using double quotes so that shell can expand $SERVER and also used alternate delimiter ~ because / is part of your variable.

anubhava
  • 761,203
  • 64
  • 569
  • 643
1

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.

Mark Reed
  • 91,912
  • 16
  • 138
  • 175