如何知道文件是否是二进制文件?
例如,编译的c文件。
我想从某个目录读取所有文件,但是我想忽略二进制文件。
使用实用程序file
,示例用法:
$ file /bin/bash /bin/bash: Mach-O universal binary with 2 architectures /bin/bash (for architecture x86_64): Mach-O 64-bit executable x86_64 /bin/bash (for architecture i386): Mach-O executable i386 $ file /etc/passwd /etc/passwd: ASCII English text $ file code.c code.c: ASCII c program text
file
手册页
从排除二进制文件改编
find . -exec file {} \; | grep text | cut -d: -f1
我用
! grep -qI . $path
唯一的缺点是我会看到它会考虑一个空的文件二进制文件,但是再次,谁来决定是否是错误的?
不理想,但简单的解决方案来检查单个文件:
grep -q "\x00" file.bin && echo Binary file. || echo Text file.
这基本上检查文件是否包含NUL字符。
因此,要使用find
实用程序递归读取所有非二进制文件,您可以执行以下操作:
find . -type f -exec sh -c 'grep -q "\x00" {} || cat {}' ";"
或者更简单的使用grep
:
grep -rv "\x00" .
对于当前文件夹,请使用:
grep -v "\x00" *
使用Perl内置的-T
文件测试运算符,最好在使用-f
文件测试运算符确定它是纯文件之后:
$ perl -le 'for (@ARGV) { print if -f && -T }' \ getwinsz.c a.out /etc/termcap /bin /bin/cat \ /dev/tty /usr/share/zoneinfo/UTC /etc/motd getwinsz.c /etc/termcap /etc/motd
这是这套的补充:
$ perl -le 'for (@ARGV) { print unless -f && -T }' \ getwinsz.c a.out /etc/termcap /bin /bin/cat \ /dev/tty /usr/share/zoneinfo/UTC /etc/motd a.out /bin /bin/cat /dev/tty /usr/share/zoneinfo/UTC
perl -E 'exit((-B $ARGV[0])?0:1);' file-to-test
可以用来检查“文件到测试”是否是二进制的。 上述命令将退出二进制文件的智慧代码0,否则退出代码将为1。
对文本文件的反向检查可以看起来像下面的命令:
perl -E 'exit((-T $ARGV[0])?0:1);' file-to-test
同样,如果“文件测试”是文本(不是二进制),上述命令将退出状态0。
阅读更多关于-B
和-T
检查使用命令perldoc -f -X
。
尝试以下命令行:
file "$FILE" | grep -vq 'ASCII' && echo "$FILE is binary"
用tr -d "[[:print:]\n\t]" < file | wc -c
来排除二进制文件是一种强制性的行为tr -d "[[:print:]\n\t]" < file | wc -c
tr -d "[[:print:]\n\t]" < file | wc -c
,但它也没有启发式的猜测。
find . -type f -maxdepth 1 -exec /bin/sh -c ' for file in "$@"; do if [ $(LC_ALL=C LANG=C tr -d "[[:print:]\n\t]" < "$file" | wc -c) -gt 0 ]; then echo "${file} is no ASCII text file (UNIX)" else echo "${file} is ASCII text file (UNIX)" fi done ' _ '{}' +
不过,使用grep -a -m 1 $'[^[:print:]\t]' file
蛮力方法似乎要快得多。
find . -type f -maxdepth 1 -exec /bin/sh -c ' tab="$(printf "\t")" for file in "$@"; do if LC_ALL=C LANG=C grep -a -m 1 "[^[:print:]${tab}]" "$file" 1>/dev/null 2>&1; then echo "${file} is no ASCII text file (UNIX)" else echo "${file} is ASCII text file (UNIX)" fi done ' _ '{}' +
关闭巴赫的建议 ,我认为 – --mime-encoding
是从file
获得可靠信息的最佳标志。
file --mime-encoding [FILES ...] | grep -v '\bbinary$'
将打印file
相信有一个非二进制编码的文件。 如果你只是想要文件名,你可以通过cut -d: -f1
来修改: encoding
。