Using sed to edit config files

If you have a script which installs something, you often also want to automatically adjust a config file after installation. You can use the unix tool ‘sed’ for that.

Here are some examples, which assume that you have a parameter called ‘Test’ in the config file which is set to a value using ‘=’ character, e.g. test.conf

# This is some fake config file
Test = 123

Now you can use ‘sed’ to comment that line out, in or change the value:

# comment out
sed -i -e '/^[[:blank:]]*Test/ s/^#*/#/' test.conf

# comment in
sed -i -e '/^[[:blank:]]*#[[:blank:]]*Test/ s/^[[:blank:]]*#*//' test.conf

# set the value to 'abc'
sed -i -e '/^[[:blank:]]*Test[[:blank:]]*=/ s/=.*/= abc/' test.conf

With the ‘-i’ option the file is edited in-line. If you don’t use it the (modified) file content is printed out on the command line; good for testing.

The ‘[[:blank:]]’ fields are included so that the expression also works for messy config files, where you could have things like

  #  Test
Test    =123
   Test    = 123
# etc.