Use SED to replace part of a current variable with user input variable

I’m trying to replace only part of the existing variable with a new user input variable as below:

#Current Variable:
gdbName=Test.MY.DOMAIN.COM <--I need to replace the "Test" (This can be any other string not just Test e.g. CDB79 etc.) part only in this variable with new user input variable. 

#New user input variable:
read -p "Enter CDB Name : "  CDBName

#I tried the following line:
sed -i "s/gdbName=*.MY.DOMAIN.COM/gdbName=$CDBName/" somefile.txt

but it replaces the whole variable.

Any suggestions?

Note: I am updating the variable in a file.

Asked By: Ali


Assuming you want to modify a file wherein you have some line,


Then this could be done using

sed "s/^(gdbName)=Test./1=$CDBName./" somefile

or, if you need to be more generic and not specify the Test string, you could match any string not containing a dot (including the empty string):

sed "s/^(gdbName)=[^.]*./1=$CDBName./" somefile

These commands replaces the start of the line, up to the first dot, with the variable name (the string gdbName), an equal sign, and the value of the shell variable CDBName.

It is assumed that the user input in CDBName does not contain &, /, or any backslash-encoded character sequences special to sed.

In either case, a shell script does not need to define any variable called gdbName.

Your attempt removes the trailing part of the domain name because you are explicitly asking sed to match and replace it.

Answered By: Kusalananda

To set the new name dynamically, by a variable, for instance (here only shown for the permanent change):

Close to your attempt:

sed -i "s/gdbName=*.MY.DOMAIN.COM/gdbName=$CDBName/" somefile.txt

sed -i "s/gdbName=.*.MY.DOMAIN.COM/gdbName=$CDBName.MY.DOMAIN.COM/" somefile.txt

Note that dots in regular expressions match any character, but including the dot itself, so masking the dot here is a bit over the top, for most cases.

Answered By: user unknown
Categories: Answers Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.