RAnand
RAnand

Reputation: 89

bash command to replace a part of a string with an environment variable

I have a configuration file abc.config which looks like the following, made up of key-value pairs:

<add key="Server.HostName" value="local_host" />
<add key="Server.Tcp.Port" value="8080" />
<add key="Server.IPAddress" value="xx.xx.xx.xx" />

I need a bash script that will read the entire line 1 and replace just "local_host" with an environment variable, MSYSTEM, which will be passed at run time.

What I have tried is

sed -i s/'<add key="Server.HostName" value="local_host" />'/"<add key="Server.HostName" value="$MSYSTEM" />" /c/app/abc.config

but it gives me an error

sed: -e expression #1, char 56: unknown option to `s'

Is sed command the correct way to do this? If not what should I do?

Upvotes: 0

Views: 306

Answers (1)

KamilCuk
KamilCuk

Reputation: 140970

Your command after some fixing could look like this:

sed -i 's@<add key="Server.HostName" value="local_host" />@<add key="Server.HostName" value="'"$MSYSTEM"'" />@' /c/app/abc.config

I start with '. Then if I have to get a variable I do '"$variable"' — end single quotes, start double quotes, get the variable, end double quote, re-start single quotes — and continue with the single quotes quoting.

The s/// command may be delimited by any character. I chose s@@@ here, choose a character that will not appear in the MSYSTEM variable.

Upvotes: 1

Related Questions