用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
- 用ShellScript批量轉換文件的編碼
- Bash 和 ShellScript 的基础
- shellscript之简单的if语句
- shellScript之函数之间的调用
- 文件的批量重命名
- 用NSUrlSession批量下载文件并保存文件的处理
- Linux利用shellscript编写查看局域网的网络状态
- linux 批量文件的移动
- matlab批量文件的重命名
- 批量更改文件的后缀名
- 批量SCP文件的脚本
- 批量处理文件的方法
- 【Python】批量文件的编辑
- 批量更改文件的扩展名
- 批量修改文件的方法
- 批量删除文件(由批量删除.svn文件引起的)
- 用Visual C++实现文件间批量转换的功能
- 用rm命令批量删除文件的潜在问题
- dede后台崩溃,打不开,不能操作左边菜单
- Union和Union All的区别
- Cannot find javahl, svnkit nor command line svn client
- jquery 倒计时 简洁版
- DEDE 调用文章图片
- 用ShellScript批量轉換文件的編碼
- C# 获取天气 JSON解析
- 列表
- Android系统进程间通信(IPC)机制Binder中的Client获得Server远程接口过程源代码分析
- 一位禅师临终前的忏悔和忠言
- dedecms 友情链接的详细分析
- 二十七、权限控制的自定义注解实现方式
- iphone ios 屏幕,statusbar,状态栏,标签栏尺寸,高度
- 元组