I'm new to linux and grep, and trying to find my way around.

By using find -name *.java I am able to find the names of all of the java files in a particular directory. Suppose I want to count the number of times foo occurs in these files, how would I do that?

I'be been trying things like:

grep -r "foo" *.java

and getting responses like:

grep:  *.java:  No such file or directory

Any ideas?

link|improve this question

80% accept rate
2  
Dupe: superuser.com/questions/3512 – innaM Aug 6 '09 at 14:52
Sorry, I'll look harder next time. Remarkable that the questions were so similar. – Eric Wilson Aug 6 '09 at 14:59
The title of 3512 could be a lot better. "Basic grep usage question" doesn't tell you a whole lot about the actual question. We'll probably have more dupes unless that is fixed. – Richard Hoskins Aug 6 '09 at 16:10
@richardhoskins, fixed. – John T Aug 6 '09 at 16:52
feedback

2 Answers

up vote 8 down vote accepted
find . -name '*.java' | xargs grep <your pattern here>
link|improve this answer
3  
Better yet, use null terminated items so that a file name with a space in it doesn't get split into two file names: find . -name '*.java' -type f -print0 | xargs -0 grep <your pattern here> – CoverosGene Aug 6 '09 at 14:55
1  
@CoverosGene: You can use the --replace option to xargs to handle that -- like this: ... | xargs --replace grep "{}" <pattern> – arathorn Aug 6 '09 at 14:59
thanks much, I knew there must be a command that does what xargs does. – Eric Wilson Aug 6 '09 at 15:00
feedback

There is a tool specially designed for this type of need: ack.

ack is a tool like grep, aimed at programmers with large trees of heterogeneous source code

Also read the "Top 10 reasons to use ack instead of grep." at the ack page.

link|improve this answer
1  
Meh. A real unix tool needs a recursive name that referring its heritage... like abtg [ABTG's Better Than Grep], or something. ACK? The only good think about that is that the author of the improved NACK already have a name picked out ;) – Mikeage Aug 7 '09 at 11:27
One of the reasons I really love ack is that you can specify file types. For example, I with "ack --html <pattern>" it searches all my .html, .htm, .xhtml, .dhtml, etc. files in one go. – Mark van Lent Aug 7 '09 at 11:54
Ack has pretty much replaced grep for me. – Ryan Thompson Sep 8 '09 at 23:38
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.