Linux 下转换文本文件编码

Windows 下用 notepad++ 可以非常方便的使用不同的编码格式对文本文件进行查看以及转换编码格式,Linux 下需要结合 file 和 iconv 这两个工具才能完成类似的工作(vi 的话,大多数人搞不懂终端编码、文件编码、内部编码,当然搞懂了的话和 notepad++ 差不太多[1]),当然也做不到 notepad++ 的可视化。

查看文件编码:

~$ file -i x1
x: text/plain; charset=us-ascii
~$ file -i x2
x: text/plain; charset=iso-8859-1
~$ file -i x3
x: text/plain; charset=utf-8
~$ file -i x4
x: text/plain; charset=utf-8
~$ file -i x5
x: text/plain; charset=utf-16be
~$ file -i x6
x: text/plain; charset=utf-16le

iconv 转换的命令行如下:

~$ iconv -f from-encoding -t to-encoding -o outputfile inputfile(s)

如:

~$ iconv -f cp936 -t utf-8 -o utf8 gb2312

可以使用 iconv -l 查看支持的编码类型:

~$ iconv -l
The following list contains all the coded character sets known.  This does
not necessarily mean that all combinations of these names can be used for
the FROM and TO command line parameters.  One coded character set can be
listed with several different names (aliases).

  437, 500, 500V1, 850, 851, 852, 855, 856, 857, 860, 861, 862, 863, 864, 865,
  866, 866NAV, 869, 874, 904, 1026, 1046, 1047, 8859_1, 8859_2, 8859_3, 8859_4,
  8859_5, 8859_6, 8859_7, 8859_8, 8859_9, 10646-1:1993, 10646-1:1993/UCS4,
  ANSI_X3.4-1968, ANSI_X3.4-1986, ANSI_X3.4, ANSI_X3.110-1983, ANSI_X3.110,
  ARABIC, ARABIC7, ARMSCII-8, ASCII, ASMO-708, ASMO_449, BALTIC, BIG-5,
  BIG-FIVE, BIG5-HKSCS, BIG5, BIG5HKSCS, BIGFIVE, BRF, BS_4730, CA, CN-BIG5,
  ...

由于通过 Linux/ssh 终端不能正确查看文件转换之后文件是否有乱码,因此还是用 notepad++ 更靠谱(如果是桌面系统,wine 一个 notepad++ 绝对比 Linux 下任何编辑器都靠谱),iconv 在确切知道文件编码(文件编码是个很复杂的问题,file -i 显示的 iso-8859-1 绝对不能拿来当成一个编码直接使用,而需要使用 GB2312/CP936 这样的与 locale 有关的编码),且需要批量操作的场景下比较有优势。

参考资料

[1] Character Encoding Tricks for Vim

https://spin.atomicobject.com/2011/06/21/character-encoding-tricks-for-vim/


最后修改于 2019-01-24

- 目录 -