用ShellScript批量轉換文件的編碼

来源:互联网 发布:汤姆索亚历险记 知乎 编辑:程序博客网 时间:2024/05/01 07:14

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

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


#!/bin/bashfunction 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`doif test -d $1"/"$file; thendelete_old_encoded_files $1"/"$file;fidonefor file in `ls $1 | grep encoded_utf8`dorm -f $1"/"$file;done}function doencode() {#轉碼為utf-8for file in `ls $1`dolocal filepath=$1"/"$file#只對文件編碼轉換,文件夾略過if [ ! -d $filepath ]; then#如果轉換成功,刪除原文件,並把轉換後的文件重命名為原文件的名字if (iconv -f $2 -t UTF8 $filepath > $filepath.encoded_utf8) ; thenrm -f $filepath;mv $filepath.encoded_utf8 $filepath;#否則,則轉失敗(可能是圖片文件),刪除轉換時產生的臨時文件,保留舊的原文件else rm -f $filepath.encoded_utf8;fifidone} #遍歷所有文件夾function iterate() {for file in `ls $1`doif test -d $1"/"$file; theniterate $1"/"$file $2;fidonedoencode $1 $2;}#如果參數不等於2,顯示用法if [ $# -ne 2 ]; thenusage#如果參數1不是一個目錄的路徑,提示錯誤elif [ ! -d $1 ]; thenecho "";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