Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Easiest way to recursively find and replace?

Tags:

grep

replace

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.

like image 583
Eric Wilson Avatar asked Mar 31 '10 14:03

Eric Wilson


People also ask

How do I find and replace recursively in Linux?

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.

Can you use sed recursively?

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.

How do I search for a directory in recursively?

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 .


2 Answers

GNU find

find /path -type f -iname "*.txt" -exec sed -i.bak 's/foo/bar/g' "{}" +;
like image 164
ghostdog74 Avatar answered Sep 18 '22 01:09

ghostdog74


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.

like image 21
Jerry Coffin Avatar answered Sep 19 '22 01:09

Jerry Coffin