: mark
轉(zhuǎn)碼工具,支持UTF-8轉(zhuǎn)GBK和GBK轉(zhuǎn)UTF-8
孔令飛@2012-05-07
mark
#set -x
scode="gbk"
dcode="utf-8"
function Usage()
{
cat EOF
Usage: conv [OPTIONS] [DIR]
[-u] GBK to UTF-8
[-g] UTF-8 to GBK
EOF
exit 1
}
#將當(dāng)前目錄下所有普通文件進(jìn)行轉(zhuǎn)碼 GBK to UTF-8
function g2u()
{
local dir=$1
printf "Convering $dir ......"
for file in $(ls $dir)
do
file="$dir/$file"
if [ -f $file ];then
coding=$(file -b $file | cut -d ' ' -f1)
#進(jìn)行轉(zhuǎn)碼
if [ "$coding" = "ISO-8859" ];then
local tmpfile=$(mktemp)
Fright=$(stat -c %a $file)
Fuser=$(stat -c %U $file)
Fgro=$(stat -c %G $file)
iconv -f $scode -t $dcode $file > $tmpfile || Usage
mv $tmpfile $file
chmod $Fright $file
chown $Fuser:$Fgrp $file
fi
fi
done
printf " done\n"
}
function u2g()
{
local dir=$1
printf "Convering $dir ......"
for file in $(ls $dir)
do
file="$dir/$file"
if [ -f $file ];then
coding=$(file -b $file |cut -d ' ' -f1)
#進(jìn)行轉(zhuǎn)碼
if [ "$coding" = "UTF-8" ];then
local tmpfile=$(mktemp)
Fright=$(stat -c %a $file)
Fuser=$(stat -c %U $file)
Fgro=$(stat -c %G $file)
iconv -f $dcode -t $scode $file > $tmpfile || Usage
mv $tmpfile $file
chmod $Fright $file
chown $Fuser:$Fgrp $file
fi
fi
done
printf " done\n"
}
[ $# -ne 2 ] Usage
while getopts ug opt
do
case $opt in
u) echo "Convert gbk coding to utf-8 ...."
for dir in $(find $2 -type d)
do
g2u $dir
done
g) echo "Convert utf-8 coding to gbk ...."
for dir in $(find $2 -type d)
do
u2g $dir
done
*) Usage
exit 1
esac
done
exit 0
標(biāo)簽:馬鞍山 赤峰 許昌 金昌 邵陽 淘寶邀評 巴彥淖爾 婁底
巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《shell實(shí)現(xiàn)字符編碼轉(zhuǎn)換工具分享》,本文關(guān)鍵詞 shell,實(shí)現(xiàn),字符,編碼,轉(zhuǎn)換,;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請?zhí)峁┫嚓P(guān)信息告之我們,我們將及時(shí)溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無關(guān)。