Recursive find and replace
Monday, 08 February 2010
From time to time I find myself wanting to replace a bit of text, in multiple files, throughout a huge directory tree (particularly in the case of a WordPress migration).
Here’s a method I frequently use (other examples I’ve seen out there make use of perl, xargs, grep, etc.):
user@host:~$ cd Directory_To_Start_From user@host:~$ find . -type f -exec sed -i 's/Text_To_Find/Replacement_Text/g' {} \;
The find command will return a list of all the files in the directory tree and execute the sed command on each one it locates. In the example below, I added the “-name” option to the find command to allow for working only on files with the .js extension:
user@host:~$ cd website user@host:~$ find . -type f -name "*.js" -exec sed -i 's/var pageName="example page";/var pageName="Final Page";/g' {} \;
In the next one, the text to find and replace has special characters (in this case the ‘/’ in the URL).
user@host:~$ cd website user@host:~$ find . -type f -exec sed -i 's/http:\/\/www.example.com\/old_directory\//http:\/\/newsubdomain.example.com\/new_directory\//g' {} \;
See the following links to read more about escaping special characters:
- Bash Hackers Wiki – Quotes and escaping
- Unix / Linux Shell Scripting Tutorial – Escape Characters
- Advanced Bash-Scripting Guide