这是我寻求的解决方案:
#!/bin/bash
result="$( { stdout="$(curl -Lsv -compressed "$1")" ; } 2>&1; echo "--SePaRaToR--"; echo "$stdout")";
echo '
found:'
echo "$result" | grep -o '\(charset\|encoding\)[ ]*=[ ]*["]*[a-zA-Z0-9_: -]*'
echo ' '
status=1
charset="ISO_8859-1" #set default
# 1: HTTP Content-Type: header
# 2: <meta> element in the page
# 3: <xml> element in the page
regex='.*(charset|encoding)\s*=\s*["]*([a-zA-Z0-9_: -]*)'
if [[ "$result" =~ $regex ]]
then
charset="${BASH_REMATCH[2]}"
status=2
echo "match succes: $charset"
else
echo "match fail: $charset : ${BASH_REMATCH[2]}"
fi
if [[ "$charset" == *utf-8* || "$charset" == *UTF-8* ]]
then
charset='NotModified'
else
echo "iconv '$charset' to UTF-8//TRANSLIT"
html=$(echo "$result" | iconv -f"$charset" -t'UTF-8//TRANSLIT')
if [ $? -ne 0 ]
then
echo "translit failed : iconv '$charset' to UTF-8//IGNORE"
html=$(echo "$result" | iconv -f"$charset" -t"UTF-8//IGNORE")
if [ $? -ne 0 ]
then
charset="ISO_8859-1"
echo "ignore failed : iconv '$charset' to UTF-8//IGNORE"
html=$(echo "$result" | iconv -f"$charset" -t"UTF-8//IGNORE")
status=4
fi
status=3
fi
fi
echo "charset: '$charset' , status: '$status'"
默认是 w3c推荐。
它不是 100% 准确,但速度很快,而且 99% 的时间都能完成工作。
希望它可以帮助处于相同情况的人。
也感谢所有回答。