我需要找到放在一个目录中的所有文件的编码。有没有办法找到所使用的编码?
file命令不能做到这一点。
我感兴趣的编码是ISO 8859-1。如果是其他编码,我想将文件移动到另一个目录。
我需要找到放在一个目录中的所有文件的编码。有没有办法找到所使用的编码?
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估计文件编码
其他回答
听起来你在找恩卡。它可以猜测甚至在编码之间进行转换。看看手册页就知道了。
否则,使用file -i (Linux)或file -i (OS X)。这将输出文件的mime类型信息,其中还将包括字符集编码。我也找到了它的手册页:)
在Perl中,使用Encode::Detect。
file -bi <file name>
如果你喜欢对一堆文件这样做
for f in `find | egrep -v Eliminate`; do echo "$f" ' -- ' `file -bi "$f"` ; done
我正在使用以下脚本
找到所有匹配FILTER和SRC_ENCODING的文件 创建它们的备份 将它们转换为DST_ENCODING (可选)删除备份
#!/bin/bash -xe
SRC_ENCODING="iso-8859-1"
DST_ENCODING="utf-8"
FILTER="*.java"
echo "Find all files that match the encoding $SRC_ENCODING and filter $FILTER"
FOUND_FILES=$(find . -iname "$FILTER" -exec file -i {} \; | grep "$SRC_ENCODING" | grep -Eo '^.*\.java')
for FILE in $FOUND_FILES ; do
ORIGINAL_FILE="$FILE.$SRC_ENCODING.bkp"
echo "Backup original file to $ORIGINAL_FILE"
mv "$FILE" "$ORIGINAL_FILE"
echo "converting $FILE from $SRC_ENCODING to $DST_ENCODING"
iconv -f "$SRC_ENCODING" -t "$DST_ENCODING" "$ORIGINAL_FILE" -o "$FILE"
done
echo "Deleting backups"
find . -iname "*.$SRC_ENCODING.bkp" -exec rm {} \;
我在一个需要跨平台支持的项目中工作,遇到了很多与文件编码相关的问题。
我做了这个脚本来转换所有的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估计文件编码