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

file命令不能做到这一点。

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


当前回答

在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

其他回答

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

我做了这个脚本来转换所有的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估计文件编码

在Perl中,使用Encode::Detect。

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

用法:

~> uchardet file.java
UTF-8

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

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

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

在Python中,你可以使用chardet模块。