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

file命令不能做到这一点。

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


当前回答

我在一个需要跨平台支持的项目中工作,遇到了很多与文件编码相关的问题。

我做了这个脚本来转换所有的utf-8:

#!/bin/bash
## Retrieve the encoding of files and convert them
for f  `find "$1" -regextype posix-egrep -regex ".*\.(cpp|h)$"`; do
  echo "file: $f"
  ## Reads the entire file and get the enconding
  bytes_to_scan=$(wc -c < $f)
  encoding=`file -b --mime-encoding -P bytes=$bytes_to_scan $f`
  case $encoding in
    iso-8859-1 | euc-kr)
    iconv -f euc-kr -t utf-8 $f > $f.utf8
    mv $f.utf8 $f
    ;;
  esac
done

我使用了一个黑客来读取整个文件,并使用文件-b——mime-encoding -P bytes=$bytes_to_scan $f估计文件编码

其他回答

uchardet -从Mozilla移植的编码检测器库。

用法:

~> uchardet file.java
UTF-8

各种Linux发行版(Debian、Ubuntu、openSUSE、Pacman等)都提供二进制文件。

file -bi <file name>

如果你喜欢对一堆文件这样做

for f in `find | egrep -v Eliminate`; do echo "$f" ' -- ' `file -bi "$f"` ; done

在Debian中你也可以使用:encguess:

$ encguess test.txt
test.txt  US-ASCII

由于它是一个perl脚本,它可以安装在大多数系统上,通过安装perl或脚本作为独立的,如果perl已经安装。

$ dpkg -S /usr/bin/encguess
perl: /usr/bin/encguess

在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

使用这个命令:

for f in `find .`; do echo `file -i "$f"`; done

您可以列出一个目录和子目录中的所有文件以及相应的编码。

如果文件名称中有空格,请使用:

IFS=$'\n'
for f in `find .`; do echo `file -i "$f"`; done

记住,它会将当前Bash会话解释器更改为“空格”。