In Mac OS, how do I find and replace a certain text in all of a directory and its sub directories?
1 Answer
Use a combination of find(1)
and sed(1)
:
# Find all files under the directory hierarchy rooted at 'root', and replace
# all instances of the regular expression 'pattern' with 'replacement' in all
# of those files:
find root -type f -exec sed -i~ 's/pattern/replacement/g' '{}' '+'
If you run into command line length limitations, replace the '+'
at the end with ';'
. This will make it run slower (since it was to fork a new process for each file), but it will not have a danger of too long of a command line for sed
.
You can also only do the replacement for certain files by adding appropriate filters to find
(e.g. -name *.txt
to only replace .txt files).