78
find . -type f | xargs file | grep text | cut -d':' -f1 | xargs grep -l "TEXTSEARCH" {}

it's a good solution? for find TEXTSEARCH recursively in only textual files

stefcud
  • 2,220
  • 4
  • 27
  • 37

3 Answers3

263

You can use the -r(recursive) and -I(ignore binary) options in grep:

$ grep -rI "TEXTSEARCH" .
  • -I Process a binary file as if it did not contain matching data; this is equivalent to the --binary-files=without-match option.
  • -r Read all files under each directory, recursively; this is equivalent to the -d recurse option.
Zoltán
  • 21,321
  • 14
  • 93
  • 134
kev
  • 155,172
  • 47
  • 273
  • 272
8

If you know what the file extension is that you want to search, then a very simple way to search all *.txt files from the current dir, recursively through all subdirs, case insensitive:

grep -ri --include=*.txt "sometext" *
Benjamin Loison
  • 3,782
  • 4
  • 16
  • 33
Mark B
  • 528
  • 5
  • 7
  • 5
    The `--include` flag needs a glob pattern enclosed in quotes. This as it is won't work, more like this: `--include="*.txt"`. – tralph3 Dec 23 '20 at 06:07
7

Another, less elegant solution than kevs, is, to chain -exec commands in find together, without xargs and cut:

find . -type f -exec bash -c "file -bi {} | grep -q text" \; -exec grep TEXTSEARCH {} ";" 
user unknown
  • 35,537
  • 11
  • 75
  • 121
  • 26
    Look at the next answer. Do not use this one. – coder543 Jun 24 '13 at 14:42
  • Which problem do you see with this one? – user unknown Jun 25 '13 at 16:17
  • 3
    it is complex and inefficient. The built-in grep tool is able to solve the question with a single flag. This answer may do the job, but it is a poor solution, in light of the other one's existence. Wouldn't you agree? – coder543 Jun 25 '13 at 19:15
  • 2
    It depends much on the number of files to search and their size. Often it isn't of interest if a search runs for 0.01s or 0.001s. Still, kevs answer is much faster to type, more easy to remember and even if you don't remember any of them more easy to look up. However, I guess my command shows how to chain filters with find which is a useful thing to see, so I don't like to delete it, even While I upvoted kevs solution. – user unknown Jun 25 '13 at 22:48
  • 10
    Not all versions of grep support `-I` – user606723 Sep 13 '13 at 18:39
  • This answer is more flexible and useful because the result of find command can be filtered by mime type. – Big Shield Aug 23 '17 at 08:52
  • There could be differences in performance over remote filesystems, and this answer is more flexible in terms of what precise kinds of files should be searched. The other solution is definitely preferred, but this is an interesting tool for someone's toolbox. – Justin W Jul 25 '20 at 07:09