Linux下对文件进行编码转换(简体→繁体,繁体→(2)

#!/bin/bash

#文件名
fname=$1
#临时文件,用来保存转换的结果
tmpfile="cc`date +%0H%0M%0S`.liu"
#没有输入文件名
if [ -z ${fname} ] ; then
echo "Bad file name. ";
exit;
fi
#输入的文件不存在
if [ ! -f ${fname} ] ; then
echo "File is not existed.FILE="${fname};
exit;
fi
################################################
# f_code:现有文件的编码,当不太清楚现有文件的编码的时候,
# 可以同时指定的几种可能的编码
# t_code:希望转换成的目标编码
################################################
#比如要将GB2312或者UTF-8的文件转换成BIG5(繁体)文件
t_code="BIG5" #目标编码
f_code="GB2312 UTF-8" #可以转换的文字编码

#判断系统文字编码是否为GB2312,是的话则将BIG5或者UTF-8编码的文件转换成系统一样
#的GB2312
echo $LANG | grep -i GB2312> /dev/null
if [ $? -eq 0 ] ; then
t_code="GB2312" #目标编码
f_code="BIG5 UTF-8" #可以转换的文字编码
fi

#判断系统文字编码是否为BIG5, 是的话则将GB2312或者UTF-8编码的文件转换成系统一样
#的GB2312
echo $LANG | grep -i BIG5 > /dev/null
if [ $? -eq 0 ] ; then
t_code="BIG5" #目标编码
f_code="GB2312 UTF-8" #可以转换的文字编码
fi
#如果要把GB2312,BIG5文字编码的文件统一转换成UTF-8,则应该这样
t_code="UTF-8" #目标编码
f_code="GB2312 BIG5" #可以转换的文字编码

#当然你也可以任意设置你需要互相转换的编码,但主意要保证编码之间可以自由转换。比如
#你要将GB2312转换成某种西欧编码,则没有什么意义了。
normal_msg=""
error_msg=""
#依次尝试从可以转换的文字编码开始对文件进行编码转换
for code in ${f_code} ; do
#文字编码转换
iconv -f $code -t $t_code ${fname} > ${tmpfile}
#转换成功,一旦转换成功则不用再尝试用其他编码来读取文件
if [ $? -eq 0 ] ; then
normal_msg="ICONV SUCCESSED! FILENAME=${fname} F_CODE=$code,T_CODE=$t_code"
break
else #转换失败
if [ ! -z "${error_msg}" ] ; then
error_msg="${error_msg} "
fi
error_msg="${error_msg}ICONV FAILED! FILENAME=${fname} F_CODE=$code,T_CODE=$t_code"
fi
done
#输出转换结果消息
#转换成功,则输出转换成功消息;所有尝试转换都失败的时候,则输出所有转换失败消息
if [ -z "${normal_msg}" ] ; then
echo -e ${error_msg}
else
cp -f ${tmpfile} $fname
echo ${normal_msg}
fi

#删除临时文件
if [ -f ${tmpfile} ] ; then
rm -f ${tmpfile};
fi

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/769d3cde7ee212ed8800b9bbda6fe205.html