Replace a string in multiple files

Sometimes you need to replace a word / sentence / string that appears multiple times on a website. With the command line this is a very easy task.

This command replaces the string “old-string” with “new-string” in all files in the current directory:

sed -i 's/old-string/new-string/g'

For a recursive find and replace that will also replace strings in subfolders use this instead:

grep -rlZ 'old-string' * | xargs -0 sed -i 's/old-string/new-strjng/g'

The Z and 0 parameters are needed to handle filenames with spaces in the filename. They prevent the dreaded “No such file or directory” error message when using xargs and sed.

Replace a string in multiple files
Share this