How to grep a String in all the java files in subdirectories?

24,137

Solution 1

Use recursive grep:

grep -r "String" --include=*.java .

Solution 2

I guess the unxUtils provide the find utility. So you could try to do:

find . -name "*.java" -exec grep "String" {} \;

or

find . -name "*.java" -exec grep "String" {} \+

The first version will execute one grep command for each file found. The latter version will only execute as many grep commands as necessary but not every find version supports the + argument.

Share:
24,137
Freewind
Author by

Freewind

A programmer ([email protected])

Updated on July 29, 2020

Comments

  • Freewind
    Freewind over 3 years

    I want to use grep to find the lines contain String in all java files under current directory.

    I tried:

    grep -r "String" **/*.java
    

    But it doesn't work:

    grep : **/*.java:  no such file or directory
    

    How to write it?


    UPDATE

    I'm on windows, using the grep provided by unxUtils, which doesn't support --include parameter. Is there any other way?

  • Freewind
    Freewind almost 13 years
    thank you. I found it works on linux, but now I'm on windows. Is there any other way?
  • Freewind
    Freewind almost 13 years
    The bad news is find . -name "*.java" doesn't work for fild of unxUtils, it reports File not found - *.java. Finally, I just installed the cygwin
  • anubhava
    anubhava almost 13 years
    If you have cygwin installed same command will work on Windows as well, I have actually tried on my cygwin and it worked fine on Windows 7 as well.
  • gp-coder
    gp-coder about 9 years
    It might be helpful to add a filename as part of the search to make it easier. The print argument will help here:find . -name "*.java" -print -exec grep "String" {} \;
  • WesternGun
    WesternGun about 5 years
    ..or gitbash, as it has amounts of executable useful and full support of Windows path.