83
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

0

3 Answers 3

278

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.
Sign up to request clarification or add additional context in comments.

2 Comments

No, this one can not ignore special file, like unix socket
For anyone else who arrives here looking for an alternative to git grep so you can include checking uncommitted files and notes that this is much slower than git grep, just add -L. You'll note that including super-linter.log is slow, so add things like --exclude-dir='.[A-Za-z0-9]*' --exclude-dir=archive --exclude=super-linter.log. Then you're good to go.
9

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" * 

1 Comment

The --include flag needs a glob pattern enclosed in quotes. This as it is won't work, more like this: --include="*.txt".
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 {} ";" 

7 Comments

Look at the next answer. Do not use this one.
Which problem do you see with this one?
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?
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.
Not all versions of grep support -I
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.