[英]Convert stdout to utf8 in bash
我想将任何带有curl的网站的输出转换为数据库插入的utf8。
用法例如:
html="$(curl -iL -compressed "$link")"
##code needed to convert nonUTF8 $html to utf8, preferably without writing to file
## escape characters for insert
html_q="${html//'\'/\\\\}"
html_q="${html_q//"'"/\'}"
## the insert statement
sqlHtml='INSERT INTO `'"${tableHtml}"'` (`html`) VALUES ('"'${html_q}'"');'
mysql -u$dbUser -p$dbPass -h$dbHost -P$dbPort -D$dbName --default_character_set utf8 -A <<ENDofMESSAGE
${sqlHtml}
ENDofMESSAGE
简短的问题,简短的答案:
man iconv
现在,您还有另一个问题:确定网页的源编码是什么。 (提示:在Google中键入charsetdetector)
通常情况下,如果没有解析器,就无法正确完成。 脚本编写不会成功。 如果您的目标是存储页面,则将其视为二进制文件,进行压缩并转换为可打印形式。
这是我追求的解决方案:
#!/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 recomandation 。
它不是100%准确,但速度很快,并且99%的时间都可以做到。
希望它可以帮助处于相同情况的人。
也感谢所有回答。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.