批量转码背景与Shell脚本必要性
在软件开发过程中,经常面临大量文件需要统一更改编码格式的情况。由于iconv命令仅支持对单个文件进行转换,逐一操作效率低下,因此编写一个Shell脚本来自动化这一过程成为必要的解决方案。
完整Shell脚本批量转码实现
以下展示第一种实现方式,即通过完整的Shell脚本逻辑来执行批量转码任务。
#!/bin/sh
#
convertCodeFilePath=$1
fromCode=$2
toCode=$3
for i in {1..1}
do
[ -f $convertCodeFilePath ]
if [ $? -eq 0 ]
then
iconv -f $fromCode -t $toCode -c -o $convertCodeFilePath $convertCodeFilePath
if [ $? -ne 0 ]
then
echo $convertCodeFilePath "=>" convert code failed.
else
echo $convertCodeFilePath "=>" convert code success.
fi
break;
fi
[ -d $convertCodeFilePath ]
if [ $? -ne 0 ]
then
break;
fi
dir=`ls $convertCodeFilePath | sort -d`
for fileName in $dir
do
fileFullPatch=$convertCodeFilePath/$fileName
fileType=`echo $fileName |awk -F. '{print $2}'`
[ -d $fileName ]
if [ $? -eq 0 ]
then
continue
fi
if [ $fileType != 'sh' ] && [ $fileType != 'py' ] && [ $fileType != 'xml' ] && [ $fileType != 'properties' ] \
&& [ $fileType != 'q' ] && [ $fileType != 'hql' ] && [ $fileType != 'txt' ]
then
continue
fi
iconv -f $fromCode -t $toCode -c -o $fileFullPatch $fileFullPatch
if [ $? -ne 0 ]
then
echo $fileName "=>" convert code failed.
continue
else
echo $fileName "=>" convert code success.
fi
done
done
具体调用方法如下所示:
sh convertCode.sh /home/sam/data gbk utf-8
简洁版代码及用法示例
此外,还有一种更为精简的代码版本可供参考。
该简洁版本的用法示例如下:
cd ~/workspace/XXXProject
~/iconv_shell.sh ./ *java
接下来直接展示具体的代码实现部分。
#!/bin/bash
if [ "$#" != "2" ]; then
echo "Usage: `basename $0` dir filter"
exit
fi
dir=$1
filter=$2
echo $1
for file in `find $dir -name "$2"`; do
echo "$file"
iconv -f gbk -t utf8 -o $file $file
done
当前脚本仍有优化空间,例如将源编码和目标编码作为命令行参数传入,虽然目前暂无此需求而未实现,但具备扩展潜力。