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

发布时间:2022-04-19 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了shell实现字符编码转换工具分享脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

复制代码 代码如下:

#!/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

脚本宝典总结

以上是脚本宝典为你收集整理的shell实现字符编码转换工具分享全部内容,希望文章能够帮你解决shell实现字符编码转换工具分享所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: