Shell implements character encoding conversion tool sharing _linux shell

Source: Internet
Author: User
Tags chmod

Copy Code code as follows:

#!/bin/bash

: << Mark
Transcoding tool, support UTF-8 turn GBK and GBK to UTF-8
Kong Lingfei @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)
Todo
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)
Todo
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
Todo
Case $opt in
u) echo "Convert GBK coding to Utf-8 ..."
For Dir in $ (find $2-type D)
Todo
G2u $dir
Done

g) echo "Convert utf-8 coding to GBK ..."
For Dir in $ (find $2-type D)
Todo
U2G $dir
Done

*) Usage
Exit 1

Esac
Done

Exit 0

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.