How do I use sed to change my configuration files, with flexible keys and values?
sed -i -e '/central\.database =/ s/= .*/= new_value/' /path/to/file
Explanation:
-i
tells sed to save the results to the input file. Without it sed will print the results to stdout./central\.database =/
matches lines that contain the string between slashes:central.database =
. The.
is escaped since it's a special character in regex.- The
s/OLD/NEW/
part performs a substitution. The OLD string is a regular expression to match and theNEW
part is the string to substitute in. - In regular expressions,
.*
means "match anything". So= .*
matches an equal sign, space, and then anything else afterward.
Here's an example expression:
sed -i 's/^\(central\.database\s*=\s*\).*$/\1SQLTEST/' file.cfg
If you want to match stuff with /
in it, you can use another delimiter:
sed -i 's#^\(cent/ral\.data/base\s*=\s*\).*$#\1SQL/TEST#' file.cfg
Or with variable expansion:
VAL="SQLTEST"
sed -i "s/^\(central\.database\s*=\s*\).*\$/\1$VAL/" file.cfg
In your example:
sshRetValue=`sed -i "s/^\(\1$CENTRAL_DB_NAME\s*=\s*\).*\$/\1$CENTRAL_DB_VALUE/" /home/testing.txt`;
There's a \1 before $CENTRAL_DB_NAME that's invalid. Also, sed doesn't print it's return value. This is the preferred way to check return values:
sed -i "s/^\($CENTRAL_DB_NAME\s*=\s*\).*\$/\1$CENTRAL_DB_VALUE/" /home/testing.txt;
sed_return_value=$?
And ultimately piping to ssh (not tested):
sed_return_value=$(ssh server <<EOF
sed -i "s/^\($CENTRAL_DB_NAME\s*=\s*\).*\$/\1$CENTRAL_DB_VALUE/" /home/testing.txt;
echo $?
EOF
)
The -i is for replacing data in the input file. Otherwise sed writes to stdout.
Regular expressions are a field of their own. It would be impossible to explain them in depth in a stackoverflow answer, unless there is some specific function that's eluding you.