How to find binary files in a directory? How to find binary files in a directory? linux linux

How to find binary files in a directory?


This finds all non-text based, binary, and empty files.

Edit

Solution with only grep (from Mehrdad's comment):

grep -rIL .

Original answer

This does not require any other tool except find and grep:

find . -type f -exec grep -IL . "{}" \;

-I tells grep to assume binary files as unmatched

-L prints only unmatched files

. matches anything else


Edit 2

This finds all non-empty binary files:

find . -type f ! -size 0 -exec grep -IL . "{}" \;


Just have to mention Perl's -T test for text files, and its opposite -B for binary files.

$ find . -type f | perl -lne 'print if -B'

will print out any binary files it sees. Use -T if you want the opposite: text files.

It's not totally foolproof as it only looks in the first 1,000 characters or so, but it's better than some of the ad-hoc methods suggested here. See man perlfunc for the whole rundown. Here is a summary:

The "-T" and "-B" switches work as follows. The first block or so ofthe file is examined to see if it is valid UTF-8 that includesnon-ASCII characters. If, so it's a "-T" file. Otherwise, that sameportion of the file is examined for odd characters such as strangecontrol codes or characters with the high bit set. If more than athird of the characters are strange, it's a "-B" file; otherwise it'sa "-T" file. Also, any file containing a zero byte in the examinedportion is considered a binary file.


My first answer to the question fell pretty much inline here using the find command. I think your instructor was looking to get you into the concept of magic numbers using the file command, which breaks them down into multiple types.

For my purposes, it was as simple as:

file * | grep executable

But it can be done in numerous ways.