Home > database >  Using 'sed' to replace a string
Using 'sed' to replace a string

Time:10-20


I have a file that contains a URL and I wish to replace this URL with a new one. This URL can be different each time so I do not wish to replace XXX with YYY but to change the value of a variable which contains the URL.

File looks like this:

APP_URL=https://test.hello.co/

I wish to change the value of APP_URL to a different URL but without success.
I am using a bash script in order to make this work.
tried using this inside my script and it didn't work.

oldline='APP_URL=https://test.hello.co'
newline='APP_URL=https://${variable}'
sudo sed -i 's/${oldline}/${newline}/g' .env

I would love to get help here!
Thank you :)

CodePudding user response:

Single quotes prevent variable interpolation.

You can usually use double quotes instead.

$: cat tst
oldurl=test.hello.co
newurl=foo.bar.com
sed "s,APP_URL=https://${oldurl}/,APP_URL=https://${newurl}/,g" file

$: cat file
APP_URL=https://test.hello.co/

$: ./tst
APP_URL=https://foo.bar.com/

CodePudding user response:

You need to remove the ' in sed and escape all / so that it doesn't think you are ending the part of s (or use other sign) Both these work (my filename is .test):

variable=aaaaaaaaaaaaaaaaaaaaaaaaa

oldline='APP_URL=\S '
newline='APP_URL=https:\/\/'$variable
sed -r s/${oldline}/${newline}/g .test

oldline='APP_URL=\S '
newline='APP_URL=https://'$variable
sed -r s-${oldline}-${newline}-g .test
  • Related