How can I know if a file is a binary file?
For example, compiled c file.
I want to read all files from some directory, but I want ignore binary files.
Here is a simple solution to check for a single file using BSD grep (on macOS/Unix):
grep -q "\x00" file && echo Binary || echo Text
which basically checks if file consist NUL character.
Using this method, to read all non-binary files recursively using find
utility you can do:
find . -type f -exec sh -c 'grep -q "\x00" {} || cat {}' ";"
Or even simpler using just grep
:
grep -rv "\x00" .
For just current folder, use:
grep -v "\x00" *
Unfortunately the above examples won't work for GNU grep, however there is a workaround.
Since GNU grep
is ignoring NULL characters, it's possible to check for other non-ASCII characters like:
$ grep -P "[^\x00-\x7F]" file && echo Binary || echo Text
Note: It won't work for files containing only NULL characters.