views:

1028

answers:

7

I have had to do this several times, usually when trying to find in what files a variable or a function is used.

I remember using xargs with grep in the past to do this, but I am wondering if there are any easier ways.

+8  A: 
grep -r REGEX .

Replace . with whatever directory you want to search from.

Chris Jester-Young
Warning, -r only works with some versions of grep.
Chas. Owens
+1  A: 

grep -r if you're using GNU grep, which comes with most Linux distros.

On most UNIXes it's not installed by default so try this instead:

find . -type f | xargs grep regex

CaptainPicard
+1  A: 

If you use the zsh shell you can use

grep REGEX **/*

or

grep REGEX **/*.java

This can run out of steam if there are too many matching files.

The canonical way though is to use find with exec.

find . -name '*.java' -exec grep REGEX {} \;

or

find . -type f -exec grep REGEX {} \;

The 'type f' bit just means type of file and will match all files.

Darren Greaves
+4  A: 

This is one of the cases for which I've started using ack (http://petdance.com/ack/) in lieu of grep. From the site, you can get instructions to install it as a Perl CPAN component, or you can get a self-contained version that can be installed without dealing with dependencies.

Besides the fact that it defaults to recursive searching, it allows you to use Perl-strength regular expressions, use regex's to choose files to search, etc. It has an impressive list of options. I recommend visiting the site and checking it out. I've found it extremely easy to use, and there are tips for integrating it with vi(m), emacs, and even TextMate if you use that.

rjray
A: 

I suggest changing the answer to:

grep REGEX -r .

The -r switch doesn't indicate regular expression. It tells grep to recurse into the directory provided.

Scott
+2  A: 

If you're looking for a string match, use

fgrep -r pattern .

which is faster than using grep. More about the subject here: http://www.mkssoftware.com/docs/man1/grep.1.asp

Gabriel Gilini
A: 

The portable method* of doing this is

find . -type f -print0 | xargs -0 grep pattern

-print0 tells find to use ASCII nuls as the separator and -0 tells xargs the same thing. If you don't use them you will get errors on files and directories that contain spaces in their names.

* as opposed to grep -r, grep -R, or grep --recursive which only work on some machines.

Chas. Owens