我需要找到放在一个目录中的所有文件的编码。有没有办法找到所使用的编码?

file命令不能做到这一点。

我感兴趣的编码是ISO 8859-1。如果是其他编码,我想将文件移动到另一个目录。


当前回答

在PHP中,你可以像这样检查它:

显式指定编码列表:

php -r "echo 'probably : ' . mb_detect_encoding(file_get_contents('myfile.txt'), 'UTF-8, ASCII, JIS, EUC-JP, SJIS, iso-8859-1') . PHP_EOL;"

更准确的"mb_list_encodings":

php -r "echo 'probably : ' . mb_detect_encoding(file_get_contents('myfile.txt'), mb_list_encodings()) . PHP_EOL;"

在第一个示例中,您可以看到我使用了一个可能匹配的编码列表(检测列表顺序)。 为了得到更准确的结果,你可以使用所有可能的编码:mb_list_encodings()

注意mb_*函数需要php-mbstring:

apt-get install php-mbstring

其他回答

我知道您对更一般的答案感兴趣,但是ASCII中的优点通常也适用于其他编码。下面是一个Python单行程序,用于确定标准输入是否是ASCII。(我很确定这在Python 2中可以工作,但我只在Python 3上测试过。)

python -c 'from sys import exit,stdin;exit()if 128>max(c for l in open(stdin.fileno(),"b") for c in l) else exit("Not ASCII")' < myfile.txt

在PHP中,你可以像这样检查它:

显式指定编码列表:

php -r "echo 'probably : ' . mb_detect_encoding(file_get_contents('myfile.txt'), 'UTF-8, ASCII, JIS, EUC-JP, SJIS, iso-8859-1') . PHP_EOL;"

更准确的"mb_list_encodings":

php -r "echo 'probably : ' . mb_detect_encoding(file_get_contents('myfile.txt'), mb_list_encodings()) . PHP_EOL;"

在第一个示例中,您可以看到我使用了一个可能匹配的编码列表(检测列表顺序)。 为了得到更准确的结果,你可以使用所有可能的编码:mb_list_encodings()

注意mb_*函数需要php-mbstring:

apt-get install php-mbstring

您可以使用file命令提取单个文件的编码。我有一个sample.html文件:

$ file sample.html 

HTML: HTML文档,UTF-8 Unicode文本,有很长的行

$ file -b sample.html

HTML文档,UTF-8 Unicode文本,有很长的行

$ file -bi sample.html

短信/ html;charset = utf-8

$ file -bi sample.html  | awk -F'=' '{print $2 }'

utf - 8

如果谈论的是XML文件(ISO-8859-1),其中的XML声明指定了编码:<??> . xml version="1.0" encoding="ISO-8859-1" 因此,您可以使用正则表达式(例如,使用Perl)来检查每个文件是否有这样的规范。

更多信息可以在这里找到:如何确定文本文件编码。

在Cygwin中,这看起来很适合我:

find -type f -name "<FILENAME_GLOB>" | while read <VAR>; do (file -i "$<VAR>"); done

例子:

find -type f -name "*.txt" | while read file; do (file -i "$file"); done

您可以将其输送到AWK,并创建一个iconv命令,将所有内容从iconv支持的任何源编码转换为UTF-8。

例子:

find -type f -name "*.txt" | while read file; do (file -i "$file"); done | awk -F[:=] '{print "iconv -f "$3" -t utf8 \""$1"\" > \""$1"_utf8\""}' | bash