linux处理中文字符集工具集粹与详解


 
Linux对中文的支持不是很好,也不像Windows样,会对文件名,文件内容做字符集的自动转换。
 
例如,将Windows下的文件复制到Linux下,会出现一堆的乱码,这时,就要用到linux的一些字符集转换工具来处理。
 
1. 批量文件名字符集转换工具 -- convmv
下载链接:
http://download.chinaunix.net/download/0002000/1760.shtml
convmv是一个更改文件名编码方式的工具,
它甚而可以进行目录下文件名的批量转换。
 
例如,
 
将/home目录下原来文件名是gbk编码方式的全部改为utf-8格式的,
使用命令如下:
$./convmv -f gbk -t utf8 -r –notest /home
-f 文件名原编码方式;
-t 文件名要更改为的编码方式;
-r 这个目录下面的所有文件;
-notest 表示马上执行,而不是仅仅测试而已。
 
更多的功能详解可见它的帮助:
USAGE: convmv [options] FILE(S)
-f enc encoding *from* which should be converted
-t enc encoding *to* which should be converted
-r recursively go through directories
-i interactive mode (ask for each action)
--nfc target files will be normalization form C for UTF-8 (Linux etc.)
--nfd target files will be normalization form D for UTF-8 (OS X etc.)
--qfrom be quiet about the "from" of a rename (if it screws up your terminal e.g.)
--qto be quiet about the "to" of a rename (if it screws up your terminal e.g.)
--exec c execute command instead of rename (use #1 and #2 and see man page)
--list list all available encodings
--lowmem keep memory footprint low (see man page)
--nosmart ignore if files already seem to be UTF-8 and convert if posible
--notest actually do rename the files
--replace will replace files if they are equal
--unescape convert%20ugly%20escape%20sequences
--upper turn to upper case
--lower turn to lower case
--help print this help
 
2.  文件内容字符集转换工具 -- iconv
 
它通常是Linux系统自带的转换工具。
 
$iconv -f gbk -t utf8 -o outfile infile
-f 文件原来的编码方式;
-t 输出文件的编码方式; 
-o 输出文件名,这利用outfile表示,
 
最后跟上要更改编码方式的文件名infile 
 
这个工具有两个缺陷:
 
一个是必须先知道文件原来的编码方式, 否则将出错。
 
    这个可以用命令 "file filename" 得到。
 
二个是如果转换出错,将不会返回。
 
iconv的用法:
 
iconv命令用于转换指定文件的编码,默认输出到标准输出设备,亦可指定输出文件。
用法:iconv [选项...] [文件...]
 
有如下选项可用:
输入/输出格式规范:
-f, --from-code=名称 原始文本编码
-t, --to-code=名称 输出编码
 
信息:
-l, --list 列举所有已知的字符集
 
输出控制:
-c 从输出中忽略无效的字符
-o, --output=FILE 输出文件
-s, --silent 关闭警告
--verbose 打印进度信息
--help 给出该系统求助列表
--usage 给出简要的用法信息
-V, --version 打印程序版本号
 
3. 强大的文件内容字符集转换工具 -- enca
下载地址:
$wget http://dl.cihar.com/enca/enca-1.13.tar.gz
 
在应用上enca比iconv更完善,在中文支持上enca比iconv支持得好,
iconv当遇到不支持的中文时会跳过或者报错cannot iconving。
 
所以推荐用enca。
 
编译与安装:
$tar -jxvf enca-1.13
$cd enca-1.13
$./configure
$make
$make check
$make install
 
编译时的出错解决:
 
如果编译时遇到出错提示:
...
/usr/bin/ld: /usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../lib64/libm.a(w_exp.o):
relocation R_X86_64_32 against `a local symbol' can not be used when making a shared object;
recompile with -fPIC
/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../lib64/libm.a: could not read symbols:
Bad value
collect2: ld returned 1 exit status
make[2]: *** [libenca.la] Error 1
...
 
则需要更改它的配置选项为:
$./configure --enable-shared=no
原因详解:
http://www.gentoo.org/proj/en/base/amd64/howtos/index.xml?part=1&chap=3
使用示例:
enca -L zh_CN test.sql                      // 检查文件编码
enca -L zh_CN -x UTF-8 test.sql             // 将文件编码转换为UTF-8编码   
enca -L zh_CN -x UTF-8 <test.sql> test2.sql // 转换并另存为test2.sql

相关内容