global search and replace for all files in a directory?

80251

Distinguished
Jan 5, 2015
55
0
18,630
I know I can use grep to search for strings in all files in a directory tree. Is it possible to do a global search and replace for all files in a directory tree?
 
Solution
yes using combination of 'grep' and 'sed' very easy. If you search google/yahoo/duckduckgo you fill find 100,000+ results/examples. alternatively combination of 'find' and 'sed'. you can even use 'awk' to selectively replace elements in a data set(s)!

i write example for you:
I have tree look like this, all files contain string 'hello'. change all string to world.
~/hello/world/
./test1.txt
./test2.txt
./test3.txt
./test4.txt
./test/test1.txt
./test/test2.txt
./test/test3.txt
./test/test4.txt

Code:
cd ~/hello/world/
find . -type f -exec sed -i 's/hello/world/g' {} \;

Now all file contain string 'world'
yes using combination of 'grep' and 'sed' very easy. If you search google/yahoo/duckduckgo you fill find 100,000+ results/examples. alternatively combination of 'find' and 'sed'. you can even use 'awk' to selectively replace elements in a data set(s)!

i write example for you:
I have tree look like this, all files contain string 'hello'. change all string to world.
~/hello/world/
./test1.txt
./test2.txt
./test3.txt
./test4.txt
./test/test1.txt
./test/test2.txt
./test/test3.txt
./test/test4.txt

Code:
cd ~/hello/world/
find . -type f -exec sed -i 's/hello/world/g' {} \;

Now all file contain string 'world'
 
Solution

80251

Distinguished
Jan 5, 2015
55
0
18,630
Thanks skittle, this will save me a lot of time.

I ended up using something like:
find . -type f -name '*.[hm]' -print0
| xargs -0 perl -pi -e 's/search_regex/replacement_string/g'

The only downside is that it updates the modification date for
all files searched, regardless of whether it modified them or not.