当前位置: 移动技术网 > 网络运营>服务器>Linux > Shell脚本遍历目录并批量修改文件编码

Shell脚本遍历目录并批量修改文件编码

2017年12月12日  | 移动技术网网络运营  | 我要评论

在将windows上的jsp网页移植到linux环境中时,发现一个个的转换编码及修改默认编码类型太慢,写此脚本进行尝试文件遍历~

好久不写,手生了。

复制代码 代码如下:

#!/bin/bash
#
#
spath="/root/chengji/webroot"
dpath="/web"
# 函数开始部分
cycling(){
  filelist=`ls -1 $spath`
for filename in $filelist ; do
if [ -f $filename ] ; then 
        echo filename:$filename
        /usr/bin/iconv -f gbk -t utf-8  $spath/$filename -o  $dpath/$filename
        #cp -pv $spath/$filename  $dpath/$filename 该句为前期便利效果测试
        sed  -i  -e  's/gb2312/utf-8/g'  -e 's/gb2312/utf-8/g'  $dpath/$filename
    elif [ -d $filename ] ; then
        dpath=$dpath/$filename
        mkdir -pv $dpath
        cd $filename
        spath=`pwd`
    # next for recurse 如果遇到目录进行自我调用。。。实现深层遍历
        cycling
    # next usag: basename dirname
        dpath=`dirname $dpath`
        spath=`dirname $spath`
        cd $spath
else
        echo "file $spath/$filename is not a common file.please check."
    fi
  done
}
 # 命令开始部分
cd $spath
cycling
echo "all done."

当然,上面的代码由于使用了函数循环调用,显的很臃肿。下面来一种简单的方法,find一下:

复制代码 代码如下:

#/bin/bash
#auth: mo
#desc:
#
spath="/root/chengji"
dir=webroot
dpath="/web"
 find ${dir}   -type d  -exec mkdir -pv ${dpath}/{}  \;   
 find ${dir}  -type f -exec  iconv -f gbk -t utf-8  {} -o  ${dpath/{}  \; 
echo "the file next listed is not a common file or directory ,please check."
find  ${dir}  ! -type f  -a  ! -type d -ecec  ls -l {} \; 
find  $dpath -type f -exec sed  -i  -e  's/gb2312/utf-8/g'  -e 's/gb2312/utf-8/g'  {} \;
echo ' '
echo "all done."

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网