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.

  • Did you mean to use gdbName=*.MY.DOMAIN.COM? That means match gdbName, then 0 or more = and then any character, followed by MY.DOMAIN.COM. Maybe you wanted .* instead? What is this dbca.rsp file? Is that where the replacement should occur? So it isn't actually a variable but a file?
    – terdon
    Sep 12 at 17:15
  • Are you trying to change the contents of a shell variable named gdbName that exists in your environment, or trying to change the contents of a file that contains the line gdbName=Test.MY.DOMAIN.COM? Please edit your question to clarify. and provide concise, testable sample input and expected output.
    – Ed Morton
    Sep 12 at 17:23
  • Could $CDBName ever contain a & or \1 or / or newline?
    – Ed Morton
    Sep 12 at 17:27

2 Answers 2


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.


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.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .