Saturday 25 June 2016

Using sed to search and replace text in files within a directory

I needed to edit all files within a directory, replacing an ip address '10.0.7.52' with 'localhost'.

sed is a very powerful command line tool. All the help web pages look intimidating so, it took me a long time to appreciate and understand the basics of it.

The basic usage is:
sed [options] commands [file-to-edit]


I used:
sed -i -e 's/10\.0\.7\.52/localhost/g' *


-i option is used to edit in place on filename.

-e option indicates a command to run.

s is the command used to replace the found expression "10.0.7.52" with "localhost". The command and the two 'words' are separated by forward slashes.

g stands for "global", meaning to do this for the whole line. If you leave off the g and "10.0.7.52" appears twice on the same line, only the first "10.0.7.52" is changed to "localhost".

The backslashes are to escape the following character (the dot) otherwise, it would be interpreted as wildcard for a single character and not, as a dot in the ip address.

Finally, the asterisk states to run this on all files in the current directory.

No comments: