shell实现字符编码转换工具分享
#!/bin/bash
: << mark
转码工具,支持utf-8转gbk和gbk转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
}
#将当前目录下所有普通文件进行转码 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)
#进行转码
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)
#进行转码
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