2018年3月6日 星期二

研究 | 檔案編碼與轉碼 file encoding

如何知道檔案的編碼是什麼?

檔案的編碼可以使用 file 指令來得知

file -bi file

範例:

file -bi /etc/inittab 

結果:

text/plain; charset=us-ascii

說明:
1. text/plain 是 MIME types,格式是 [type]/[subtype],用來表示內容的類型,text/plain 表示純文字檔。 
2. 從 charset=us-ascii 可以得知 /etc/inittab 是使用 ASCII 字元集。

如何知道系統支援哪些字元集?

透過 iconv 指令可以得知系統支援的字元集

範例:

iconv -l

結果:

The following list contain 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,
  CN-GB, CN, CP-AR, CP-GR, CP-HU, CP037, CP038, CP273, CP274, CP275, CP278,
  CP280, CP281, CP282, CP284, CP285, CP290, CP297, CP367, CP420, CP423, CP424,
  CP437, CP500, CP737, CP775, CP803, CP813, CP819, CP850, CP851, CP852, CP855,
  CP856, CP857, CP860, CP861, CP862, CP863, CP864, CP865, CP866, CP866NAV,
  CP868, CP869, CP870, CP871, CP874, CP875, CP880, CP891, CP901, 
...

說明:
由於字元集很多,就不全部顯示出來。

如何改變檔案的編碼?

使用 iconv 轉換檔案的編碼
此範例將檔案的檔案編碼從 utf-8 換成 us-ascii

範例:

[william@william-fedora ~]$ cat test.utf8 
此檔案使用 utf-8 編碼

[william@william-fedora ~]$ file -bi test.utf8 
text/plain; charset=utf-8

[william@william-fedora ~]$ iconv -f utf-8 -t us-ascii -o test.ascii test.utf8 

iconv: illegal input sequence at position 0

[william@william-fedora ~]$ iconv -f utf-8 -t us-ascii -c -o test.ascii test.utf8 

[william@william-fedora ~]$ cat test.ascii 
 utf-8 

[william@william-fedora ~]$ file -bi test.ascii 
text/plain; charset=us-ascii

[william@william-fedora ~]$ od -t x1 -c test.ascii 
0000000  20  75  74  66  2d  38  20  0d  0a
              u   t   f   -   8      \r  \n
0000011

說明:
1. utf-8 是 unicode 常用的編碼方式,當檔案的內容使用了 ASCII 字元集以外的字元時可以選用 utf-8 來做編碼,但是轉成 us-ascii 後,ASCII 字元集以外的字就遺失了。

2. 範例使用檔案 test.utf8,採用 utf-8 編碼,內容是此檔案使用 utf-8 編碼,包含中文字。使用 iconv 轉換成 us-ascii 時,因為 ASCII 字元集無法表示中文字,所以會有錯誤訊息,利用參數 -c 將無法表示的字元丟棄,轉換後的結果中文字都遺失了。 

沒有留言:

張貼留言