Server Fault is a question and answer site for system and network administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Given this example folder structure:


How do I do a recursive text search on all *.txt files with grep from "/"?

("grep -r <pattern> *.txt" fails when run from "/", since there are no .txt files in that folder.)

share|improve this question
up vote 39 down vote accepted

My version of GNU Grep has a switch for this:

grep -R foo --include '*.txt' *

Described as follows:


Search only files whose base name matches GLOB (using wildcard matching as described under --exclude).

share|improve this answer

If you have a large number of files it would be useful to incorporate xargs into the command to avoid an 'Argument list too long' error.

find . -name '*.txt' -print | xargs grep <pattern>
share|improve this answer
If there are spaces in any of the file or directory names, use this form: find . -name '*.txt' -print0 | xargs -0 grep <pattern> – Jason Luther May 19 '09 at 13:37
And of course there's the issue of filenames that start with -. – T.J. Crowder Feb 7 '11 at 12:08

you might be able to make use of your zsh's EXTENDED_GLOB option (docs)

grep <pattern> **/*.txt
share|improve this answer
Only if OP is using zsh, but interesting nonetheless. – Law29 May 14 at 13:01
find . -name '*.txt' -type f -exec grep <pattern> {} \;
share|improve this answer
you might want to use "find . -name '*.txt' -type f -exec grep <pattern> {} +" instead so that it rather behaves similiar the verision with from Mark Robinson - works only with GNU find to my knowledge – Server Horror Jun 10 '09 at 8:49

Mannis answer would fork a new grep-process for every textfile. If you have lots of textfiles there, you might consider grepping every file first and pick the .txt-files when thats done:

grep -r <pattern> * | grep \.txt:

That's more disk-intensive, but might be faster anyway.

share|improve this answer

You may want to take a look at ack at, which has facilities for selecting files to search by filetype.

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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