How to use sed to replace a string in multiple files

Using sed, it is possible to do a search and replace across one or many files. The syntax is as follows:

sed -i 's/search/replace/g' [filename]

The -i option does inline editing so that the file is actually edited. Without the -i, the file is not edited, but the replacement is printed to the screen. The /g at the end is used to search globally and replace all instances.

In order to edit multiple files, the filename can be replaced with a wildcard or a wildcard with part of the filename. If a file extension is provided after the -i option, a backup of the file will be made using that extension.

For example, this command will search all files in the current directory for any instance of the word search and replace it with the word replace. A backup of each file will be created with an extension of .bak.

sed -i.bak 's/search/replace/g' *

Leave a Reply