• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

shell实现字符编码转换工具分享

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

复制代码 代码如下:

#!/bin/bash

: << mark
转码工具,支持UTF-8转GBK和GBK转UTF-8
孔令飞@2012-05-07
mark

#set -x

scode="gbk"
dcode="utf-8"

function Usage()
{
 cat << EOF
Usage: conv [OPTIONS] [DIR]
[-u] GBK to UTF-8
[-g] UTF-8 to GBK
EOF
 exit 1
}


#将当前目录下所有普通文件进行转码 GBK to UTF-8
function g2u()
{
 local dir=$1
 printf "Convering $dir ......"
 for file in $(ls $dir)
 do
  file="$dir/$file"
  if [ -f $file ];then

   coding=$(file -b $file | cut -d ' ' -f1)

   #进行转码
   if [ "$coding" = "ISO-8859" ];then
    local tmpfile=$(mktemp)
    Fright=$(stat -c %a $file)
    Fuser=$(stat -c %U $file)
    Fgro=$(stat -c %G $file)
    iconv -f $scode -t $dcode $file > $tmpfile || Usage
    mv $tmpfile $file &&
    chmod $Fright $file
    chown $Fuser:$Fgrp $file
   fi
  fi
 done
 printf "      done\n"
}

function u2g()
{
 local dir=$1
 printf "Convering $dir ......"
 for file in $(ls $dir)
 do
  file="$dir/$file"
  if [ -f $file ];then

   coding=$(file -b $file |cut -d ' ' -f1)

   #进行转码
   if [ "$coding" = "UTF-8" ];then
    local tmpfile=$(mktemp)
    Fright=$(stat -c %a $file)
    Fuser=$(stat -c %U $file)
    Fgro=$(stat -c %G $file)
    iconv -f $dcode -t $scode $file > $tmpfile || Usage
    mv $tmpfile $file &&
    chmod $Fright $file
    chown $Fuser:$Fgrp $file
   fi
  fi
 done
 printf "      done\n"
}

[ $# -ne 2 ] && Usage

while getopts ug opt
do
 case $opt in
  u) echo "Convert gbk coding to utf-8 ...."
  for dir in $(find $2 -type d)
  do
   g2u $dir
  done

  g) echo "Convert utf-8 coding to gbk ...."
  for dir in $(find $2 -type d)
  do
   u2g $dir
  done

  *) Usage
  exit 1

 esac
done

exit 0


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
shell编程之实现windows回收站功能分享发布时间:2022-02-11
下一篇:
win下调用putty执行命令脚本分享发布时间:2022-02-11
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap