用ShellScript批量轉換文件的編碼

最近研究了下ShellScript,寫了一個工具,來批量轉換文件的編碼為UTF-8,理論上應該支持Linux和MacOSX,現貼出源碼:

聲明:該Script有刪除源文件的操作,在使用前請先備份,因此而造成數據丟失的本人概不負責!


#!/bin/bash
function usage() {
	echo "";
	echo "Usage: tencoder <dest_dir> <from_encode>";
	echo "";
	exit 1;
}

function test_encode() {
	echo "Test encoded file." >> ~/test_encoded.tmp;
	iconv -f $2 -t UTF8 ~/test_encoded.tmp > ~/test_encoded.tmp || exec sh -c "rm -f ~/test_encoded.tmp; exit 1;";
	rm -f ~/test_encoded.tmp;
}

function delete_old_encoded_files() {
	for file in `ls $1`
	do
		if test -d $1"/"$file; then
			delete_old_encoded_files $1"/"$file;
		fi
	done
	
	for file in `ls $1 | grep encoded_utf8`
	do
		rm -f $1"/"$file;
	done
}

function doencode() {
	#轉碼為utf-8
	for file in `ls $1`
	do
		local filepath=$1"/"$file
		#只對文件編碼轉換,文件夾略過
		if [ ! -d $filepath ]; then
			#如果轉換成功,刪除原文件,並把轉換後的文件重命名為原文件的名字
			if (iconv -f $2 -t UTF8 $filepath > $filepath.encoded_utf8) ; then
				rm -f $filepath;
				mv $filepath.encoded_utf8 $filepath;
			#否則,則轉失敗(可能是圖片文件),刪除轉換時產生的臨時文件,保留舊的原文件
			else 
				rm -f $filepath.encoded_utf8;
			fi
		fi
	done
} 

#遍歷所有文件夾
function iterate() {
	for file in `ls $1`
	do
		if test -d $1"/"$file; then
			iterate $1"/"$file $2;
		fi
	done
	doencode $1 $2;
}

#如果參數不等於2,顯示用法
if [ $# -ne 2 ]; then
	usage

#如果參數1不是一個目錄的路徑,提示錯誤	
elif [ ! -d $1 ]; then
	echo "";
	echo "No such diretory -> $1"
	echo "";
	exit 1;
else
	#測試參數2(該編碼是否正確)
	test_encode $1 $2;
	#刪除以前的encode過的文件
	delete_old_encoded_files $1;
	#開始遍歷
	iterate $1 $2;
fi


使用方法:

將該段script復制保存為文件,如utf8encoder.sh,加上運行權限,使用格式如下:

# utf8encoder.sh <需要轉編碼的文件夾> <源編碼格式>


例:

# utf8encoder.sh /Users/tim/myfolder GB18030

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值