How to Change File Encoding
Table of Contents
1. 转换文件编码
下面介绍 Linux 下转换文本文件编码的几种方法。
1.1. iconv
使用 iconv
工具可以进行转换。iconv 的命令格式如下(很容易记住:-f from-code、-t to-code):
$ iconv -f encoding -t encoding inputfile
比如,将一个 GBK 编码的文件转换成 UTF-8 编码:
$ iconv -f GBK -t UTF-8 file1.txt -o file2.txt
1.2. recode
使用 recode
工具可以转换文件编码。
下面是把 1.txt 从 GBK 编码转换成 UTF-8 编码:
$ recode GBK..UTF-8 file1.txt
下面是使用 recode
实现 dos2unix 等功能:
alias dos2unix='recode dos/CR-LF..l1' alias unix2win='recode l1..windows-1250' alias unix2dos='recode l1..dos/CR-LF'
参考: man recode
1.3. vim
在 Vim 中可以转换文件编码(Vim 正确识别源编码后才能使用这种方法),比如将一个文件转换成 UTF-8 编码:
:set fileencoding=utf-8
通过 :set fileencoding
可以查看文件当前编码,这个文件编码仅是 Vim 自动识别的,不一定是正确的文件编码。如果 Vim 自动识别错误,则不能通过 set fileencoding=XXX
的方式来转换编码!
2. 检测文件编码(uchardet)
使用工具 uchardet 可以检测文件当前使用的编码。如:
$ uchardet *.txt 1.txt: GB18030 2.txt: UTF-8 3.txt: ASCII