I實現了下面的bash腳本,它適用於我。
它首先嚐試從file --mime-encoding
返回的編碼iconv
到utf-8
。
如果失敗,它會遍歷所有編碼並顯示原始文件和重新編碼文件之間的差異。它跳過產生大差異輸出的編碼(由MAX_DIFF_LINES
變量或第二個輸入參數定義的「大」),因爲這些很可能是錯誤的編碼。
如果因使用此腳本而發生「不良事件」,請不要責怪我。那裏有一個rm -f
,所以有怪物。我試圖通過在隨機後綴文件上使用它來防止不利影響,但我沒有做出任何承諾。
測試達爾文15.6.0。
#!/bin/bash
if [[ $# -lt 1 ]]
then
echo "ERROR: need one input argument: file of which the enconding is to be detected."
exit 3
fi
if [ ! -e "$1" ]
then
echo "ERROR: cannot find file '$1'"
exit 3
fi
if [[ $# -ge 2 ]]
then
MAX_DIFF_LINES=$2
else
MAX_DIFF_LINES=10
fi
#try the easy way
ENCOD=$(file --mime-encoding $1 | awk '{print $2}')
#check if this enconding is valid
iconv -f $ENCOD -t utf-8 $1 &> /dev/null
if [ $? -eq 0 ]
then
echo $ENCOD
exit 0
fi
#hard way, need the user to visually check the difference between the original and re-encoded files
for i in $(iconv -l | awk '{print $1}')
do
SINK=$1.$i.$RANDOM
iconv -f $i -t utf-8 $1 2> /dev/null > $SINK
if [ $? -eq 0 ]
then
DIFF=$(diff $1 $SINK)
if [ ! -z "$DIFF" ] && [ $(echo "$DIFF" | wc -l) -le $MAX_DIFF_LINES ]
then
echo "===== $i ====="
echo "$DIFF"
echo "Does that make sense [N/y]"
read $ANSWER
if [ "$ANSWER" == "y" ] || [ "$ANSWER" == "Y" ]
then
echo $i
exit 0
fi
fi
fi
#clean up re-encoded file
rm -f $SINK
done
echo "None of the encondings worked. You're stuck."
exit 3
根據我的經驗,file(1)命令在猜測文件的編碼方面一直很不錯。我不知道它是否足夠聰明,可以使用文件的com.apple.TextEncoding擴展屬性。 – 2016-08-04 03:16:03