I'm a linux newbie. I need to search for a string "teststring" in all *.java files coming under /home/user1/ (including subfolders). How can I do it in linux via shell command.
-
There have been several questions regarding regex searching files in subdirectories from the command-lineRobotHumans– RobotHumans2010-11-28 15:12:07 +00:00Commented Nov 28, 2010 at 15:12
-
a quick search turned up this question: superuser.com/questions/208271/… not exactly what you are looking for, but instead of exec cp you could cat/grep whateverRobotHumans– RobotHumans2010-11-28 15:16:32 +00:00Commented Nov 28, 2010 at 15:16
-
I can list the file having the extension with find /home/user1 -name *.java How to use grep on that?softwarematter– softwarematter2010-11-28 15:23:57 +00:00Commented Nov 28, 2010 at 15:23
-
find . -type f -print0 | xargs -0 grep -l "some string"Nick Dong– Nick Dong2022-12-08 07:12:59 +00:00Commented Dec 8, 2022 at 7:12
5 Answers
The easiest way is to use GNU grep's features:
grep -r --include '*.java' teststring /home/user1
If you're ever on another unix variant that doesn't have GNU grep, here's a portable way:
find /home/user1 -name '*.java' -exec grep teststring {} +
-
nice didn't know about this grep featureRobotHumans– RobotHumans2010-11-28 15:52:07 +00:00Commented Nov 28, 2010 at 15:52
-
2If you're searching the current dir and all files it's
grep -r teststring .Chris Moschini– Chris Moschini2014-06-25 17:16:46 +00:00Commented Jun 25, 2014 at 17:16
using ack you just type: cd /home/user01 && ack --java teststring
-
1or
ack --java teststring /home/user01Andy Lester– Andy Lester2010-12-01 03:43:43 +00:00Commented Dec 1, 2010 at 3:43
For this ack aka ack-grep its the killer app in my mind ;)
You can ack some_string /in/path_y to find some_string in path_y
Or simpler ack some_other_string to find some_other_sting in current dir.
Found it. Posting it as it might help someone.
find /home/user01 -name *.java | xargs grep "teststring"
Please correct if there is any better way.
-
3Generally, you should use
-print0and-0when pipingfindintoxargsto work properly with files that may have spaces or newlines in their names:find /home/user01 -name *.java -print0 | xargs -0 grep "teststring"Dennis Williamson– Dennis Williamson2010-11-28 15:38:50 +00:00Commented Nov 28, 2010 at 15:38