Easiest way to recursively find and replace?

I want to recursively search the text file directory and replace every occurrence of foo in the files with bar . What is the easiest way to do this?

I assume grep will do the job on a single line, but I cannot find an example of this.

I work in OS X.

+7
replace grep
source share
5 answers

Find GNU

 find /path -type f -iname "*.txt" -exec sed -i.bak 's/foo/bar/g' "{}" +; 
+13
source share

grep used only to find things, not to change them.

For modifications using a grep-like interface, you usually use sed . sed itself does not support any recursion - it only works on one file at a time. To add this, you usually use find to find files containing the template you want, then run sed to modify the file.

+3
source share

ZH

 sed -i 's/foo/bar/g' **/*.txt 
+2
source share

There is a good free text editor that will make it simple and easy: TextWrangler .

0
source share

try this: grep -rl "foo".|xargs sed -i 's/foo/bar/g'

0
source share

All Articles