47

Given this example folder structure:

/folder1/file1.txt
/folder1/file2.djd
/folder2/file3.txt
/folder2/file2.fha

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.)

Brent
  • 22,219
  • 19
  • 68
  • 102
Anders Sandvig
  • 649
  • 2
  • 9
  • 10

7 Answers7

63

My version of GNU Grep has a switch for this:

grep -R --include='*.txt' $Pattern

Described as follows:

--include=GLOB

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

Andrew Schulman
  • 8,561
  • 21
  • 31
  • 47
Kyle Brandt
  • 82,107
  • 71
  • 302
  • 444
20

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>
Mark
  • 754
  • 1
  • 7
  • 12
2

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

grep <pattern> **/*.txt
santa
  • 121
  • 2
1

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

Andy Lester
  • 740
  • 5
  • 16
0

It's 2019 and there's no way I would still use grep for recursive text searching.

IMHO todays answers should include ripgrep:

rg <pattern> -ttxt
santa
  • 121
  • 2
0
find . -name '*.txt' -type f -exec grep <pattern> {} \;
innaM
  • 1,428
  • 9
  • 9
  • you might want to use "find . -name '*.txt' -type f -exec grep {} +" instead so that it rather behaves similiar the verision with from Mark Robinson - works only with GNU find to my knowledge – Martin M. Jun 10 '09 at 08:49
0

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.

Commander Keen
  • 1,253
  • 7
  • 11