Append or modify keys in conf files using sed/bash one-liner

Posted by Jeff on Stack Overflow See other posts from Stack Overflow or by Jeff
Published on 2012-11-19T15:10:54Z Indexed on 2012/11/19 17:00 UTC
Read the original article Hit count: 179

Filed under:
|

I often have to modify files such as sysctl.conf, and I'm familiar with using sed to replace existing values.

Is there a way to append the new key/value pair to the file if sed wasn't able to replace it?

For instance, using this example: modify config file using bash script

sed -c -i "s/\($TARGET_KEY *= *\).*/\1$REPLACEMENT_VALUE/" $CONFIG_FILE

How could I add the $TARGET_KEY = $REPLACEMENT_VALUE new line to $CONFIG_FILE using the same sed expression with slight changes?

And on a related topic, how can I force creation of $CONFIG_FILE if it didn't exist?

© Stack Overflow or respective owner

Related posts about bash

Related posts about configuration-files