指定文件的这个目录:
$ file *
1.txt: UTF-8 Unicode (with BOM) text, with CRLF line terminators
2.pdf: PDF document, version 1.5
3.pdf: PDF document, version 1.5
4.dat: data
5.txt: ASCII text
6.jpg: JPEG image data, JFIF standard 1.02, aspect ratio, density 100x100, segment length 16, baseline, precision 8, 2833x972, frames 3
7.html: HTML document text, UTF-8 Unicode text, with very long lines, with no line terminators
8.js: UTF-8 Unicode text
9.xml: XML 1.0 document text
A.pl: a /opt/local/bin/perl script text executable, ASCII text
B.Makefile: makefile script text, ASCII text
C.c: c program text, ASCII text
D.docx: Microsoft Word 2007+
你可以看到,是纯ASCII的文件只有5.txt,9.xml,和A-C。其余的是根据file的二进制或UTF。
您可以使用Bash glob遍历文件并使用file来测试每个文件。这节省不必解析的file为文件名的输出,但依赖于file精确识别您认为什么是“文”:
for fn in *; do
[ -f "$fn" ] || continue
fo=$(file "$fn")
[[ $fo =~ ^"$fn":.*text ]] || continue
echo "$fn"
done
如果您不能使用file,这当然是最简单的方法,你可以打开文件并查找二进制字符。使用Perl为:
for fn in *; do
[ -f "$fn" ] || continue
head -c 2000 "$fn" | perl -lne '$tot+=length; $cnt+=s/[^[:ascii:]]//g; END{exit 1 if($cnt/$tot>0.03);}'
[ $? -eq 0 ] || continue
echo "$fn"
done
在这种情况下,我找了ASCII与非ASCII的前2000个字节的文件的百分比。 YMMV,但允许查找file将报告为UTF的文件(因为它具有二进制BOM),但大多数文件是ascii。
对于该目录中,这两个Bash脚本报告(与我的每个文件的注释):
1.txt # UTF file with a binary BOM but no UTF characters -- all ascii
4.dat # text based configuration file for a router. file does not report this
5.txt # Pure ascii file
7.html # html file
8.js # Javascript sourcecode
9.xml # xml file all text
A.pl # Perl file
B.Makefile # Unix make file
C.c # C source file
由于file不考虑所有的ASCII文件4.dat是文本,它不被首次报道Bash脚本,但在第二个。否则 - 相同的输出。