Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> Linux 系統教學 >> Linux 教學

Linux 文件編碼轉換實戰:enca、convmv、iconv 完全指南

編輯:Linux 教學

Linux 系統中處理跨平台文件時,編碼不一致是常見痛點。本文匯總三大核心工具——enca 檢測、convmv 文件名轉碼、iconv 內容轉碼——的安裝與實戰用法。

1. 檢測文件編碼:enca

# 安裝
sudo apt-get install enca   # Debian/Ubuntu
sudo yum install enca       # CentOS/RHEL

# 檢測單個文件
enca filename

# 批量檢測
enca *

輸出示例:UTF-8、GBK、Big5 等。

2. 文件名批量轉碼:convmv

# 安裝
sudo apt-get install convmv

# 基本語法
convmv -f 源編碼 -t 目標編碼 [選項] 文件名

# 常用選項
-r              遞歸處理子目錄
--notest        真正執行(默認僅預覽)
--list          顯示支持的編碼列表
--unescap       URL 解碼(如 %20 → 空格)

# 實例:UTF-8 文件名 → GBK
convmv -f UTF-8 -t GBK --notest -r 目錄名

3. 文件內容批量轉碼:iconv

# 單文件轉換
iconv -f 源編碼 -t 目標編碼 輸入文件 -o 輸出文件

# 實例:GBK → UTF-8
iconv -f GBK -t UTF-8 file1.txt -o file2.txt

# 批量轉換當前目錄所有文件為 UTF-8
for f in *; do
    iconv -f GBK -t UTF-8 "$f" -o "${f}.utf8" && mv "${f}.utf8" "$f"
done

4. 組合拳:enca + iconv 自動化

# 使用 enca 自動檢測並轉換為 UTF-8
enca -x UTF-8 *

-x 參數指定目標編碼,enca 會自動檢測源編碼並轉換。

常見編碼對照表

中文環境常見說明
GBK / GB2312簡體中文 Windows 默認
Big5繁體中文傳統編碼
UTF-8通用 Unicode 實現,Linux 默認
GB18030國家標準,GBK 超集

避坑指南

  • 先備份:convmv 默認 --notest 預覽模式,確認無誤再執行
  • 編碼名大小寫:iconv -l 查看準確名稱(如 UTF-8 非 utf8)
  • BOM 頭:Windows UTF-8 帶 BOM,Linux 可能識別異常,可用 sed -i '1s/^\xEF\xBB\xBF//' 移除
  • 文件名 vs 內容:convmv 只改文件名,iconv 只改內容,兩者互不影響

總結

enca 看編碼,convmv 改文件名,iconv 改內容。三工具配合,解決 99% Linux 編碼遷移問題。

Copyright © Windows教程網 All Rights Reserved