views:

143

answers:

5

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.

+2  A: 

GNU find

find /path -type f -iname "*.txt" -exec sed -i.bak 's/foo/bar/g' "{}" +;
ghostdog74
+1  A: 

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.

Jerry Coffin
A: 

This isn't a command-line solution, but try out Komodo Edit (free from http://www.activestate.com) and use their multi-file search/replace tools. They support GREP and file-type inclusion/exclusion, etc. You can even create macros in Javascript or Python for frequently used replacements, etc.

alt text

(This included an image from www.freeimagehosting.net, but apparently it isn't showing up.)

Robusto
@Nick Presta: I'm not saying this can't be done on the command line, I'm saying my suggestion of Komodo Edit is not a command-line solution. Please read the whole sentence.
Robusto
Sorry. Early morning comments are bad.
Nick Presta
A: 

There's a nice free text editor that will do this kind of thing simply and easily: TextWrangler.

Paul R
+1  A: 

zsh

sed -i 's/foo/bar/g' **/*.txt
wRAR
I get `sed: 1: "**/*.txt": invalid command code *`.
FarmBoy
You're doing it wrong. And/or not in zsh.
wRAR