In place editing of a file with sed

When writing a file modification script I find it annoying (read: boring) to write the logic of saving the file under a different name, moving to override original and then cleaning up. This is what I recently had to do and instead decided to look around at what other options were available, one of which was sed.

The following command will replace the word testdomain with proddomain.

$ echo ‘www.testdomain.com’ > test.txt
$ cat test.txt 
www.testdomain.com
 

$ sed -i ” s/testdomain/proddomain/ test.txt
$ cat test.txt
www.proddomain.com

The key to how this works is the -i ” argument of the sed command. -i specifies the file extension, by passing an empty string it uses the same file.