Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linux command: How to 'find' only text files?

Tags:

linux

find

search

After a few searches from Google, what I come up with is:

find my_folder -type f -exec grep -l "needle text" {} \; -exec file {} \; | grep text 

which is very unhandy and outputs unneeded texts such as mime type information. Any better solutions? I have lots of images and other binary files in the same folder with a lot of text files that I need to search through.

like image 262
datasn.io Avatar asked Jan 22 '11 10:01

datasn.io


People also ask

How do you search all the .TXT files?

find / -type f -name *. txt to find all . txt files, assuming you only have one hdd. And then just use grep to search in these files.

How do I search for text in Linux?

Grep is a Linux / Unix command-line tool used to search for a string of characters in a specified file. The text search pattern is called a regular expression. When it finds a match, it prints the line with the result. The grep command is handy when searching through large log files.

How do I find all files containing specific text in Unix?

Without a doubt, grep is the best command to search a file (or files) for a specific text. By default, it returns all the lines of a file that contain a certain string. This behavior can be changed with the -l option, which instructs grep to only return the file names that contain the specified text.


1 Answers

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.

like image 59
crudcore Avatar answered Oct 02 '22 10:10

crudcore