日期:2014-05-16  浏览次数:20637 次

LINUX修改文件字符集

        有些情况下,我们需要修改文件的字符集,以便解决乱码或者其他问题。在linux下,操作系统为我们提供了ICONV这个命令,下面我们来看一下这个命令的具体使用方法。

[root@oadata ~]# iconv --help
用法: iconv [选项...] [文件...]
转换给定文件的编码。

 输入/输出格式规范:
  -f, --from-code=名称     原始文本编码
  -t, --to-code=名称       输出编码

 信息:
  -l, --list                 列举所有已知的字符集

 输出控制:
  -c                         从输出中忽略无效的字符
  -o, --output=FILE          输出文件
  -s, --silent               关闭警告
      --verbose              打印进度信息

  -?, --help                 给出该系统求助列表
      --usage                给出简要的用法信息
  -V, --version              打印程序版本号

Mandatory or optional arguments to long options are also mandatory or optional
for any corresponding short options.

For bug reporting instructions, please see:
<http://www.gnu.org/software/libc/bugs.html>.
        如果要查看某个文件的字符信息,linux同样提供了file函数:

[root@oadata ~]# file --help
Usage: file [OPTION]... [FILE]...
Determine file type of FILEs.

  -m, --magic-file LIST      use LIST as a colon-separated list of magic
                               number files
  -z, --uncompress           try to look inside compressed files
  -b, --brief                do not prepend filenames to output lines
  -c, --checking-printout    print the parsed form of the magic file, use in
                               conjunction with -m to debug a new magic file
                               before installing it
  -f, --files-from FILE      read the filenames to be examined from FILE
  -F, --separator string     use string as separator instead of `:'
  -i, --mime                 output mime type strings
  -k, --keep-going           don't stop at the first match
  -L, --dereference          causes symlinks to be followed
  -n, --no-buffer            do not buffer output
  -N, --no-pad               do not pad output
  -p, --preserve-date        preserve access times on files
  -r, --raw                  don't translate unprintable chars to \ooo
  -s, --special-files        treat special (block/char devices) files as
                             ordinary ones
      --help                 display this help and exit
      --version              output version information and exit

[root@oadata ~]# file -i a.log
a.log: text/plain; charset=us-ascii

单文件的字符集转换:

[oracle@oadata dir1]$ ls -l
总计 4
-rw-r--r-- 1 oracle oinstall 22 10-12 13:14 utf8.txt
[oracle@oadata dir1]$ file -i utf8.txt 
utf8.txt: text/plain; charset=utf-8
[oracle@oadata dir1]$ iconv -f utf-8 -t gbk -o gbk.txt utf8.txt 
[oracle@oadata dir1]$ ls -l
总计 8
-rw-r--r-- 1 oracle oinstall 15 10-12 13:43 gbk.txt
-rw-r--r-- 1 oracle oinstall 22 10-12 13:14 utf8.txt
[oracle@oadata dir1]$ file -i gbk.txt 
gbk.txt: text/plain; charset=iso-8859-1

对某目录下的文件进行字符集转换:

for i in `find ./ -name *.php` ; 
do echo $i;iconv -c -f gb18030 -t utf8 $i -o /tmp/iconv.tmp;
mv /tmp/iconv.tmp $i; 
done