Search code examples
linuxbashfileshellcat

shell one-liner to cat a file only if its ASCII format file


Is it possible to write a one-liner to cat a file only if it is a text file, and not if it is a binary?

Something like:

echo "/root/mydir/foo" | <if file is ASCII then cat "/root/mydir/foo"; else echo "file is a binary">

Solution

  • You can use the output of the file command with the --mime and -b option.

    $ file -b --mime filename.bin 
    application/octet-stream; charset=binary
    

    The -b option suppresses the filename from being printed in the output so you don't have to worry about false matching the filename and --mime will give you the character set.

    You can use grep to test for the occurrence of charset=binary

    $ file -b --mime filename.bin | grep -q "charset=binary"
    

    You can then use the exit status of grep and the &&, || operators to cat the file or echo a message.

    $ echo filename | xargs -I% bash -c 'file -b --mime % | grep -q "charset=binary" || cat % && echo "binary file"'
    

    Finally xargs is used to plug in the filename from the previous command echo filename and replace the symbol % in our binary testing command.