Having Fun With sed

July 14th, 2009 | Tags: , , , ,

If you ever need to search a configuration file (or any other kind of file for that matter) for a parameter in order to replace the value, you can use `sed`.  For example, if there was an entry of

Host=a.b.c.d

But you want to replace it with:

Host=a.b.c.e

Instead of opening the file, finding the parameter, changing it, and save and exiting, you can use sed to do the work for you:

echo ‘Host=a.b.c.d’ | sed -e ‘s/^Host=.*/Host=a.b.c.e/’

That is the basic statement, but it can be modified to search and replace in a text file (let’s say it’s called ‘file.txt’):

sed -e ‘s/^Host=.*/Host=a.b.c.e/’ file.txt > /tmp/file.txt && mv /tmp/file.txt file.txt

Now, what if you want to keep the current value of Host and append more values to it so it will read:

Host=a.b.c.d,a.b.c.e

Just use this sed statement:

sed ‘s/^Host=.*$/&,a.b.c.e/’

  1. August 13th, 2009 at 17:59
    Reply | Quote | #1

    More fun includes commenting a line out if you don’t know what the whole line is:

    sed ‘s/.*string/#&/’