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

file命令不能做到这一点。

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


当前回答

下面是一个在Mac OS X上使用file -I和iconv的示例脚本。

对于你的问题,你需要使用mv而不是iconv:

#!/bin/bash
# 2016-02-08
# check encoding and convert files
for f in *.java
do
  encoding=`file -I $f | cut -f 2 -d";" | cut -f 2 -d=`
  case $encoding in
    iso-8859-1)
    iconv -f iso8859-1 -t utf-8 $f > $f.utf8
    mv $f.utf8 $f
    ;;
  esac
done

其他回答

我知道您对更一般的答案感兴趣,但是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

听起来你在找恩卡。它可以猜测甚至在编码之间进行转换。看看手册页就知道了。

否则,使用file -i (Linux)或file -i (OS X)。这将输出文件的mime类型信息,其中还将包括字符集编码。我也找到了它的手册页:)

使用这个命令:

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

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

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

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

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

在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

您可以使用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