I need to manage a configuration file in Linux using a shell script, that will read and write settings to and from the cfg
file. I have following function to write a new value
of a key
in existing config file used in my script.
set_setting() {
sed -i "s/$1=[^ ]*/$1=$2/" $3
}
Usage:
set_setting keyname NewValue /home/Config.cfg
Thus, this would replace the value of keyname
in Config.cfg
to NewValue
.
I also have a function get_setting
which uses source
command to read the config file. It accepts similarly two parameters, keyname
and the source config file, and returns the value
of the supplied key.
Now the problem is that, I have config file as follows.
name=Abc
surname=Xyz
And when I call the set_setting
function as set_setting name Def /home/Config.cfg
, ideally it should change value of name
from Abc
to Def
, but along with changing value of key name
, it also changes the value of surname
from Xyz
to Def
resulting into following in config file.
name=Def
surname=Def
I suspect this is due to having the term "name" common in both keys, as when I changed the key surname
to surnames
, it worked as expected and only value of name
was changed. Also note that, the value for the key can be anything except the space.
I'm new to shell scripting and recently discovered sed
command.
I've also refered to SO questions this and this. While both of them were quite helpful, I'm stuck with above mentioned situation.
You should anchor your match to the beginning of the line:
sed -i "s/^$1=[^ ]*/$1=$2/" $3
Note the ^
in front of $1
. This regex operator anchors the expression to the beginning of the line, effectively requiring the name being everything from the first character to the =
sign. There's also an end-of-line anchor called $
(which you do not need here).