JP's Laboratory

Posts / Code / Photos / Videos / Contact

Modifying setup files with sed

Written: 20130406

Occationally I've found the need to make a script that will replace the end of a single line in text file. As an example we could take an openvpn setup file, which has an entry for the server that the client should connect to. The file could look like this:

remote oldhost
proto udp

The user might have modified and added more options, so we only want to change the line that starts with remote. A perfect tool for this job is the stream editor sed. It has a find and replace function, which is used like this:

$ cat input_file.txt |sed 's/old/new/g'

This will replace the string "old" with "new" everywhere in the file. The 'old' part of the command is actually a regular expression. The character just after the 's' in 's/old/new/g' is used to specify the escape character, in this case '/', but you can select almost any character.

So now we can run sed and replace the line 'remote oldhost' with the new host 'remote newhost':

$ cat setup.txt |sed 's/remote oldhost/remote newhost/g'

But this will fail if the user has changed the remote address. Which might ok depending on the situation. But in case we want to change it anyway, we might change the sed command to use a regular expression instead:

$ cat setup.txt |sed -E 's/remote[ |\t]+.*/remote newhost/g'

Now we will replace any line starting with 'remote' and which has one or more spaces or tabs leading to the server address, which itself can consist of any characters.

The sed shipped with OS X seems only to support basic regular expressions by default, so be careful if you want it to run on that platform too. That is why I have not used the '\s' here. The '-E' option is actually for making sed use a more modern version of regular expression on OS X. It should also work on Linux platforms, even though it is not mentioned in the Sed's manual page.

comments powered by Disqus