Modify config file using bash script
A wild stab in the dark for modifying a single value:
sed -c -i "s/\($TARGET_KEY *= *\).*/\1$REPLACEMENT_VALUE/" $CONFIG_FILE
assuming that the target key and replacement value don't contain any special regex characters, and that your key-value separator is "=". Note, the -c option is system dependent and you may need to omit it for sed to execute.
For other tips on how to do similar replacements (e.g., when the REPLACEMENT_VALUE has '/' characters in it), there are some great examples here.
Hope this helps someone. I created a self contained script, which required config processing of sorts.
#!/bin/bashCONFIG="/tmp/test.cfg"# Use this to set the new config value, needs 2 parameters. # You could check that $1 and $2 is set, but I am lazyfunction set_config(){ sudo sed -i "s/^\($1\s*=\s*\).*\$/\1$2/" $CONFIG}# INITIALIZE CONFIG IF IT'S MISSINGif [ ! -e "${CONFIG}" ] ; then # Set default variable value sudo touch $CONFIG echo "myname=\"Test\"" | sudo tee --append $CONFIGfi# LOAD THE CONFIG FILEsource $CONFIGecho "${myname}" # SHOULD OUTPUT DEFAULT (test) ON FIRST RUNmyname="Erl"echo "${myname}" # SHOULD OUTPUT Erlset_config myname $myname # SETS THE NEW VALUE
Assuming that you have a file of key=value
pairs, potentially with spaces around the =
, you can delete, modify in-place or append key-value pairs at will using awk
even if the keys or values contain special regex sequences:
# Using awk to delete, modify or append keys# In case of an error the original configuration file is left intact# Also leaves a timestamped backup copy (omit the cp -p if none is required)CONFIG_FILE=file.confcp -p "$CONFIG_FILE" "$CONFIG_FILE.orig.`date \"+%Y%m%d_%H%M%S\"`" &&awk -F '[ \t]*=[ \t]*' '$1=="keytodelete" { next } $1=="keytomodify" { print "keytomodify=newvalue" ; next } { print } END { print "keytoappend=value" }' "$CONFIG_FILE" >"$CONFIG_FILE~" &&mv "$CONFIG_FILE~" "$CONFIG_FILE" ||echo "an error has occurred (permissions? disk space?)"