Using a shell like bash or zshell, how can I do a recursive 'find and replace'? In other words, I want to replace every occurrence of 'foo' with 'bar' in all files in this directory and its subdirectories.
How to Perform Recursive Find and Replace from the Command Line
bashfind and replaceshellzsh
Best Answer
This command will do it (tested on both Mac OS X Lion and Kubuntu Linux).
Here's how it works:
find . -type f -name '*.txt'
finds, in the current directory (.
) and below, all regular files (-type f
) whose names end in.txt
|
passes the output of that command (a list of filenames) to the next commandxargs
gathers up those filenames and hands them one by one tosed
sed -i '' -e 's/foo/bar/g'
means "edit the file in place, without a backup, and make the following substitution (s/foo/bar
) multiple times per line (/g
)" (seeman sed
)Note that the 'without a backup' part in line 4 is OK for me, because the files I'm changing are under version control anyway, so I can easily undo if there was a mistake.
To avoid having to remember this, I use an interactive bash script, as follows: