I want to recursively search through a directory of text files and replace every occurrence of foo
within the files with bar
. What is the easiest way to accomplish this?
I imagine that grep would do the job in one line, but I can't seem to find an example of this.
I'm working in OS X.
Using the find Command and the -exec <command> {} + Option. The find command can find files recursively under a given directory. Moreover, it provides an option “-exec <command> {} +” to execute a command on all found files. In this way, we invoke the sed command only once instead of n times.
Handy command to search recursively from the current directory, and use sed to replace text. egrep -R is what enables the recursive search, and sed -i enables Sed's 'in-place' mode to modify the files directly.
An easy way to do this is to use find | egrep string . If there are too many hits, then use the -type d flag for find. Run the command at the start of the directory tree you want to search, or you will have to supply the directory as an argument to find as well. Another way to do this is to use ls -laR | egrep ^d .
GNU find
find /path -type f -iname "*.txt" -exec sed -i.bak 's/foo/bar/g' "{}" +;
grep
is only used to find things, not to modify them.
For modifications with a grep-like interface, you'd typically use sed
. By itself, sed
doesn't support any kind of recursion though -- it only operates on one file at a time. To add that, you normally use find
to find the files to contain the desired pattern, then have it invoke sed
to modify the file.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With