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?

  • 2
    Dupe: superuser.com/questions/3512 – innaM Aug 6 '09 at 14:52
  • 1
    Sorry, I'll look harder next time. Remarkable that the questions were so similar. – Eric Wilson Aug 6 '09 at 14:59
  • 1
    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
  • 1
    @richardhoskins, fixed. – John T Aug 6 '09 at 16:52
find . -name '*.java' | xargs grep <your pattern here>
| improve this answer | |
  • 5
    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> – Gene Gotimer 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

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.

| 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 C. Thompson Sep 8 '09 at 23:38

What about:

grep -irn --include="*\.java" somePhrase *
| improve this answer | |

find . -type f -name '*.java' -print0 | xargs -0 grep -wo 'foo' | wc -l

| improve this answer | |
  • 3
    Welcome to SuperUser! You'll find that your answers get more attention when that are to more current questions (this one is from 2009) and when you explain why your answer is better than the already accepted one. – Eric Wilson Apr 9 '13 at 11:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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