【Bash】实现指定目录下的文件编码转换,以原文件名保存

时间:2021-07-13 17:31:57

文件名: encodeExchange.sh

Linux版本

#!/bin/bash

fEncode=UTF-8
tEncode=GBK

#fEncode=GBK
#tEncode=UTF-8

files="Classes/*"

# convert file's encoding from GBK->UTF-8 or UTF-8->GBK
convertFileEncode()
{
	if [ $# -lt 3 ]; then
		echo "Usage: convertFileEncode <files> <fromEncode> <toEncode>"
	else
		files=$1
		fEncode=$2
		tEncode=$3
		for i in `ls $files`
		do
			t=`file $i | grep UTF-8 | wc -l`
			if [ "UTF-8" = $fEncode -a $t -eq 1 ] || [ "UTF-8" = $tEncode -a $t -eq 0 ] ; then
				iconv -f $fEncode -t $tEncode $i -o $i
				echo "iconv -f $fEncode -t $tEncode $i -o $i"
			fi
		done
	fi
}

convertFileEncode "$files" $fEncode $tEncode


 在Mac OS X中发现 iconv 命令并不认识"-o"选项,所以真正转换那句要改成如下形式:

iconv -f $fEncode -t $tEncode $i > tmp; mv tmp $i