How to check if the file is a binary file and read all the files which are not?

后端 未结 13 898
走了就别回头了
走了就别回头了 2020-12-05 16:58

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.

13条回答
  •  醉梦人生
    2020-12-05 17:33

    BSD grep

    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.

    GNU grep

    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.

提交回复
热议问题