UTF-8转GBK

#!/bin/sh

# to Oudge the input data

echo "you're going to Convert the file's encoding..."
echo "before doing this,remember to backup..." 
echo "usage: ConvUTF_GB.sh utf-8/gb18030  or ConvUTF_GB.sh utf-8/gb18030 filename"

if (($# > 2)) || (($# < 1))
then 
	exit -1
fi

encoding=`echo $1 | tr '[a-z]' '[A-Z]'`

ConvFile()
{
	if [ $# != 1 ];then 
		echo "usage:ConvFile filename"
		return -1
	fi
	
	encodingType="UTF-8 ISO-8859"
	for type in ${encodingType}
	do
		# 扫描路径检查文件编码格式
		#echo ${type}
		encoding_of_file=`file $1 | grep $type` 
		if [ "$encoding_of_file" != "" ];then
			encoding_of_file=$type
	 	fi
		# 指定的转编格式和文件编码格式一致  do nothing
		if [ "$encoding_of_file" = "$encoding" ];then
			echo "指定的格式[$encoding]和文件编码格式[$encoding_of_file]一致 do nothing"
		# 文件为GBK系列的编码格式时
		elif [ "$encoding_of_file" = "ISO-8859" ];then		
			encoding_of_file=GB2312
			#且 指定编码方式为GBK时   do nothing
			encoding_GB=`echo $encoding | grep GB`
			if [ "$encoding_GB" != "" ];then
				echo "指定的转码格式[$encoding]和文件编码格式[$encoding_of_file]一致 do nothing"
			else
				iconv -f $encoding_of_file -t ${encoding} $1 -o ${1}_
 				mv ${1}_  $1
			fi
		# 编码类型未找到
		elif [ "$encoding_of_file" = "" ];then
			:
		# 文件类型和指定的编码格式不一致		
 		else
 			iconv -f ${encoding_of_file} -t ${encoding} $1 -o ${1}_
 			mv ${1}_  $1
 		fi
 	done
 	return 0
}

if [ -f "$2" ];then
	ConvFile $2
	if [ $? != 0 ];then
		echo "ConvFile failed"
		exit -1
	fi
else
	# put the files into a filelist
	#for FILENAME in $(ls .)
	listType=".c .h"
	for type in ${listType}
	do
		# 扫描路径
		echo ${type}
		find . -name "*${type}" | while read file
		do
			echo $file
			ConvFile $file
			if [ $? != 0 ];then
				echo "ConvFile failed"
				exit -1
			fi
		done
	done
fi	

编程技巧