On Sat Oct 24 1998 20:06, Coran Fisher aka The Doctor wrote:
> I have a silly question on grep usage. I'm interested in a way for
> grep to search the content of files in directory chains. I was wondering
> if someone could clue me in on a way to do this either with a switch I haven't
> figured out or by piping if necessary. I have used find piped with grep to
> search for files so I am aware of this particular ability.
There's more than one way to do this. An example might be useful:
% find /usr/include -follow -name \*.h | xargs grep time /dev/null
The find command generates a list of all the header files from /usr/include
(including symlinks).
The xargs command gives the output from the previous (find) command to
grep, one item at a time (ie, it runs the grep command for each line of
output). Very useful... it prevents the generation of a MASSIVE command
line that would otherwise be generated by doing something like this, which
runs grep once with a potentially long list of filenames:
% grep time `find /usr/include -follow -name \*.h`
The grep command looks for the string "time" (as an example).
The /dev/null is a neat trick... it forces grep to generate a filename in
the output, which would otherwise only generate matching lines (since xargs
is only giving grep one file at a time).
I have a function for bash (and a tcsh alias) that allows me to pass the
start directory for "find" and the string(s) to (e)grep for. Easy to do,
so I'll leave that for an exercise for you to do :)
Also have a look at the -exec option to find, which is also useful for this
sort of thing.
Cheers
Tony