Quick way to replace strings in a file in place

There are times when you need to replace some thing for another in a rather enormous file that could take hours if using a GUI editor Find-and-Replace function (read moving your WordPress database export from one server to another).
There’s a Unix way to achieve the same in fractions of a second. If you’re on a Mac then this will just work from your usual Terminal window. On Windows either ssh/telnet to a Unix system or use Cygwin to do this.

Here’s the command:

sed -i 's/old-word/new-word/g' filename.txt

This will replace every occurrence of ‘old-word’ with ‘new-word’ in file ‘filename.txt’. For example, if you have a dbdump.sql that you are moving from http://oldserver.com to http://www.new-server.ca the command will be the following:

sed -i 's/http:\/\/old-server.com/http:\/\/www.new-server.ca/g' dbdump.sql

(You need to remember to escape the forward slashes).

If you want to have a backup version of the original file alter the command as follows:

sed -i.bak 's/old-word/new-word/g' filename.txt

A copy of original will be created with the extention ‘.bak’

You can also execute the command on multiple files at once by replacing the ‘filename’ with the ‘*’ wildcard to alter all files with extension .txt (for example):

sed -i 's/old-word/new-word/g' *.txt

As usual, take care with your wildcards, Unix command line is unforgiving to user-error.