15

Possible Duplicate:
How can I grep in source files for some text?

What's the command to search for specific text in specific file types, recursively, under the current directory?

7
  • What do you want returned? the line the text is on? the name of the file the text is in?
    – MaQleod
    Aug 25 '11 at 21:49
  • @MaQleod: That would be good (filename + linenumber + snippet), if that's possible.
    – Phillip
    Aug 25 '11 at 21:51
  • @slhck: ack-grep is not installed; I don't have the permissions to install it.
    – Phillip
    Aug 25 '11 at 21:53
  • 1
    You wouldn't need ack-grep, you can use the examples in the question as a started (just like I said), i.e. the find | xargs | grep lines. For the specific output, man grep is always useful to read.
    – slhck
    Aug 25 '11 at 21:55
  • @slhck: Thanks, so I did grep -r --include=*.<type> "<string>" ., which worked. Unfortunately, the man page is not very straightforward in mentioning the trailing dot.
    – Phillip
    Aug 25 '11 at 22:03
13
find . -type f -name '*.extension' | xargs grep "string"

This command runs find on the local directory (.) for any files with names matching the pattern *.extension, then runs grep for "string" on the results of the find. Note that find is inherently recursive. As long as you can differentiate the files that you want from the files you don't based on name, this should work for you.

3
  • 2
    This breaks with filenames containing spaces, you should use the print0 option to be safer.
    – slhck
    Aug 25 '11 at 22:37
  • Only find -print0 will not help, also use xargs -0: find . -type f -name "*.ext" -print0 | xargs -0 grep "string"
    – BurninLeo
    Oct 7 '14 at 12:16
  • 1
    I'd recommend invoking grep with the -s (--no-messages) switch. Otherwise you may get a flood of errors messages that can mask actual matches. Jun 22 '20 at 8:52
0

To list the file name, line number in specified file and line the text appears:

for x in *.xxx; do [ -r $x ] | cat $x | grep -n TEXT | xargs printf "$x:%s\n";done

It will only run in the current directory, but it will format it nicely for you.

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