最近在用ant给java项目打jar包,但是程序运行出来之后,全部乱码,于是想到用Linux的iconv命令给java源文件转码,但是总不能一个一个地转吧,效率太低下了,于是便写了个Linux shell脚本方便以后给项目转码。
小编刚接触Linux shell脚本编程,代码看起来粗糙的话别见怪,还望多多指教,呵呵,什么也不说了,先贴出源代码:
#!/bin/bash
#递归遍历源文件目录进行编码转换
functionitem(){
forpathin$1/*
do
if [ -f $path ]
then
basename=`basename"$path"`;
if echo"begin convert:$basename"| grep"${filtername}"
then
lastpath=${path:$cutlength};
newfilename="${superdir}/${newdirbasename}/${lastpath}";
newfiledirname=${newfilename%/*};
mkdir -p"$newfiledirname";#创建目标文件所在目录
iconv -f $encodefrom -t $encodeto"${path}">"${newfilename}";
fi
else
item $path;
fi
done;
}
dirname=""; #源文件目录
superdir=""; #源文件目录上级目录
dirbasename=""; #源文件目录名
newdirbasename=""i; #目标目录目录名
cutlength=1; #源文件目录绝对路径字符串长度
encodeform=""; #源文件编码
encodeto=""; #目标文件编码
filtername=""; #过滤源文件的字符串
while getopts :f:t:d:n:hname#获取命令行参数;getopts命令,要求选项有值的话,选项后面要跟:,第一个:表示getopts会区分invalid option错误和miss option argument错误
do
case$namein
f)
fflag=1; #参数存在的标记
encodefrom=$OPTARG;;
t)
tflag=1; #参数存在的标记
encodeto=$OPTARG;;
d)
dflag=1; #参数存在的标记
dirnameval=$OPTARG;;
n)
nflag=1; #参数存在的标记
filtername=$OPTARG;;
h)
hflag=1;; #参数存在的标记
esac;
done;
if [ ! -z $hflag ] #如果存在 -h 选项则打印出帮助信息并退出脚本
then
echo ;
echo"iconvs --help";
echo" -d --dir-source the dir of -d option will be coverted";
echo" -f --encoding-from the value of -f option is the encoding of sourcefile";
echo" -t --encoding-to the value of -t option is the encoding of destfile";
echo" -n --string-filter it will filter the sourcefile by the value of -n option from sourcedir";
echo ;
exit 1;
fi
if [ -z $fflag ] #默认源文件编码为gbk
then
encodefrom="GBK";
fi
if [ -z $tflag ] #默认目标文件编码为utf-8
then
encodeto="UTF-8";
fi
if [ -z $filtername ] #默认源文件过滤字符串为 .java
then
filtername=".java";
fi
if [ ! -z $dflag ] #分析源文件目录,合成绝对路径
then
if ["${dirnameval:0:1}"="/"] #截取从索引0开始的1个长度的字符
then
dirname="$dirnameval";
else
dirname="`pwd`/$dirnameval";
fi
else
dirname="`pwd`";
fi;
dirbasename=`basename"$dirname"`; #等价于dirbasename=${basename "$dirname"};
newdirbasename="${dirbasename}-${encodeto}";
dirname=${dirname%/};
superdir="${dirname%/*}"; #大括号的扩展参数用法,%表示去除右边最小范围的匹配,这里匹配的是/*,%%表示去除右边最大范围的匹配,#和##用法相同,#去除的是左边的匹配
cutlength=$((${#superdir}+${#dirbasename}+2));
echo"from dir:$dirname";
echo"to dir:${superdir}/${newdirbasename}";
echo"from encode:${encodefrom}";
echo"to encode:${encodeto}";
echo'********************************************************************************';
item"$dirname"; #在这里进行递归遍历转码
echo'********************************************************************************';
用vi编写以上脚本,保存为iconvs.sh(当然你也可以用别的名字),假设保存位置为:/opt/iconvs.sh,接下来
cd /opt
chmod 755 iconvs.sh
bash iconvs.sh -d 源文件目录 -t 源文件编码 -f 目标文件编码 -n 过滤源文件(与grep命令匹配格式相同)
例:
bash iconvs.sh -d /opt/src -t gbk -f utf-8 -n .java
该命令会把你的/opt/src目录下的所有包含.java的文件从gbk编码转换为utf8编码,并把转换后的文件按源目录结构存放在/opt/src-utf-8文件夹中