1834237 Members
2108 Online
110066 Solutions
New Discussion

recursive grep

 
SOLVED
Go to solution
Dee_3
Regular Advisor

recursive grep

Can I grep recursively? I have a directory that has directories and I want to search the whole structure for a string - is there a way to do this?
6 REPLIES 6
harry d brown jr
Honored Contributor
Solution

Re: recursive grep

find /dir -type f -exec grep -l stringhere {} \;

live free or die
harry
Live Free or Die
James R. Ferguson
Acclaimed Contributor

Re: recursive grep

Hi Terri:

# cd thedirectory
# find . -type -f -print | xargs grep string

This will recursively search the current directory and all subdirectories looking for *files* only which contain the the string "string". The use of 'xargs' in lieu of '-exec' with the the 'find' utility is less resource intensive.

Regards!

...JRF...
Roger Baptiste
Honored Contributor

Re: recursive grep

find $DIR -type f | xargs grep

-raj
Take it easy.
harry d brown jr
Honored Contributor

Re: recursive grep

Terri,

Also, if you know that the file is less than say 1mb (1000000) then you can add that knowledge to "find":

find /searchdir -type f -size -1000000c -exec grep -l {} \;

If you aren't sure about case add the "i" option to the grep:

find /searchdir -type f -size -1000000c -exec grep -il {} \;

live free or die
harry
Live Free or Die
Alan Riggs
Honored Contributor

Re: recursive grep

I hate the garbage that results from grep'ing a compiled executable or data file.

alias regrep="find . -type f | xargs file | grep text | grep -v awk|sed 's/://' | cut -f 1| xargs grep -i"

Yes, it's a bit convoluted (thus the alias), but it works.
Robin Wakefield
Honored Contributor

Re: recursive grep

Hi Terri,

The other trick I do is:

find . -type f | xargs grep string /dev/null

You know /dev/null can *never* contain the string...but, since the grep now has more than one filename in its file list, it will print the matching line + the name of the matching file.

Rgds, Robin