文件編碼混亂是 Linux 遷移 Windows 文件時的常見痛點。本文總結三種轉換工具,從內容到文件名、從手動到智能批量,全覆蓋。
iconv [選項] [文件...]
| 參數 | 說明 |
|---|---|
-f, --from-code=編碼 | 源文件編碼 |
-t, --to-code=編碼 | 目標編碼 |
-l, --list | 列出所有已知字符集 |
-c | 忽略無效字符 |
-o, --output=文件 | 輸出文件(不指定則輸出到 stdout) |
-s, --silent | 關閉警告 |
iconv -f gb2312 -t utf-8 aaa.txt > bbb.txt
# 將 aaa.txt 從 GB2312 轉為 UTF-8,輸出到 bbb.txt
注意: Windows 寫字板生成的 txt 通常為 gb18030,指定錯誤會報 iconv: illegal input sequence at position ...。
Windows 下文件名多為 GBK,複製到 Linux 顯亂碼。convmv 專治文件名亂碼。
convmv -f GBK -t UTF-8 *.mp3 # 預覽轉換前後對比(不實際修改)
convmv -f GBK -t UTF-8 --notest *.mp3 # 真正執行轉換
convmv -f GBK -t UTF-8 -r --notest * # -r 遞歸處理子目錄
關鍵點: -f 源編碼、-t 目標編碼千萬別搞反;--notest 才真正生效。
需安裝:convmv-1.10-1.el5.noarch.rpm 或對應發行版包。
能自動識別文件編碼,支援批量轉換,極大降低門檻。
sudo apt-get install enca
enca -L zh_CN ip.txt
# Simplified Chinese National Standard; GB2312
enca -L zh_CN -x utf-8 * # 當前目錄所有文件轉 UTF-8
enca -L zh_CN -x UTF-8 file # 單文件轉換
enca -L zh_CN -x UTF-8 < file1 > file2 # 不覆蓋原文件,輸出到新文件
file filename — 系統自帶,顯示文件類型與編碼信息:set fileencoding — 直接顯示當前文件編碼在 ~/.vimrc 添加:
set encoding=utf-8 fileencodings=ucs-bom,utf-8,cp936
Vim 將按 fileencodings 列表順序嘗試識別,找不到則回退 latin-1 (ASCII)。自此告別 Vim 打開文件亂碼煩惱。