Linux command: How to 'find' only text files?
I know this is an old thread, but I stumbled across it and thought I'd share my method which I have found to be a very fast way to use find
to find only non-binary files:
find . -type f -exec grep -Iq . {} \; -print
The -I
option to grep tells it to immediately ignore binary files and the .
option along with the -q
will make it immediately match text files so it goes very fast. You can change the -print
to a -print0
for piping into an xargs -0
or something if you are concerned about spaces (thanks for the tip, @lucas.werkmeister!)
Also the first dot is only necessary for certain BSD versions of find
such as on OS X, but it doesn't hurt anything just having it there all the time if you want to put this in an alias or something.
EDIT: As @ruslan correctly pointed out, the -and
can be omitted since it is implied.
Based on this SO question :
grep -rIl "needle text" my_folder
Why is it unhandy? If you need to use it often, and don't want to type it every time just define a bash function for it:
function findTextInAsciiFiles {
# usage: findTextInAsciiFiles DIRECTORY NEEDLE_TEXT
find "$1" -type f -exec grep -l "$2" {} \; -exec file {} \; | grep text
}
put it in your .bashrc
and then just run:
findTextInAsciiFiles your_folder "needle text"
whenever you want.
EDIT to reflect OP's edit:
if you want to cut out mime informations you could just add a further stage to the pipeline that filters out mime informations. This should do the trick, by taking only what comes before :
: cut -d':' -f1
:
function findTextInAsciiFiles {
# usage: findTextInAsciiFiles DIRECTORY NEEDLE_TEXT
find "$1" -type f -exec grep -l "$2" {} \; -exec file {} \; | grep text | cut -d ':' -f1
}