Linux字符编码转换(iconv命令)

iconv是一个用于转换文件编码的Linux命令,能够将文件从一种编码转换为另一种,如UTF8到GB18030。它提供了C/C++库函数供编程使用,并在调试涉及编码转换的程序时非常有用。通过指定-f和-t参数,可以定义输入和输出编码,-l选项用于列出所有支持的编码。示例中展示了如何将GBK编码的文件转换为UTF-8编码,并提供了一个shell脚本批量转换目录下所有GBK编码的文件。
摘要由CSDN通过智能技术生成

1、简介

iconv命令是用来转换文件的编码方式的,比如它可以将UTF8编码的转换成GB18030的编码,反过来也行。JDK中也提供了类似的工具native2ascii。Linux下的iconv开发库包括iconv_open,iconv_close,iconv等C函数,可以用来在C/C++程序中很方便的转换字符编码,这在抓取网页的程序中很有用处,而iconv命令在调试此类程序时用得着。

2、语法

iconv -f encoding [-t encoding] [inputfile]...

3、选项

-f encoding :把字符从encoding编码开始转换。
-t encoding :把字符转换到encoding编码。
-l :列出已知的编码字符集合
-o file :指定输出文件
-c :忽略输出的非法字符
-s :禁止警告信息,但不是错误信息
--verbose :显示进度信息
-f和-t所能指定的合法字符在-l选项的命令里面都列出来了。

4、实例

列出当前支持的字符编码:
iconv -l
将文件file1转码,转后文件输出到fil2中:
iconv file1 -f EUC-JP-MS -t UTF-8 -o file2

5、shell脚本

#!/bin/sh


##
## convert file from GB2312 to UTF-8
##


path="$1"
unset opt
if [ "$2" = "force" ]; then
    opt="-c -s"
fi


if [ -z "$path" ]; then
    echo "nUsage: $0 <file or dir>n"
elif [ ! -e "$path" ] ; then
    echo "nERROR: destination: $path does not exist.n"
fi


if [ -f "$path" ] ; then
    echo "Converting $path (gbk --> utf-8) ... "
    if file "$path"|grep -q UTF-8 >/dev/null ; then
        echo "Already converted"
    else
        iconv -f gbk $opt -t utf-8 "$path" > /tmp/$$.tmp
        if [ $? -eq 0 ] ; then
            echo "Success"
            mv -f /tmp/$$.tmp "$path"
        else
            echo "Failed"
        fi
    fi
elif [ -d "$path" ] ; then
    path=`echo "$path/"|sed 's//'`
    find "$path" -path "$path.*" -prune -o -type f -print|while read i
    do
        dir=`dirname $i`
        file=`basename $i`
        echo "Converting $dir/$file (gbk --> utf-8) ..."
        iconv -f gbk -t utf-8 $opt "$i" > /tmp/$$.tmp 2>/dev/null
        if [ $? -eq 0 ] ; then
            echo "Success"
            mv -f /tmp/$$.tmp "$i"
        else
            echo "Failed"
        fi
    done
fi
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值