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 文字檔編碼轉換利器 iconv:單檔與批次轉換 GB2312、BIG5、UTF-8 完整指南

編輯:Linux 教學

iconv 基本語法

iconv -f 原始編碼 -t 目標編碼 輸入檔 -o 輸出檔
# 或使用重導向
iconv -f 原始編碼 -t 目標編碼 輸入檔 > 輸出檔
  • -f (--from-code):來源編碼
  • -t (--to-code):目標編碼
  • 支援編碼列表:iconv -l

常見轉換範例

1. GB2312 → BIG5

iconv -f GB2312 -t BIG5 foo.txt > foo1.txt

2. BIG5 → GB2312

iconv -f BIG5 -t GB2312 foo.txt > foo2.txt

3. GB2312 → UTF-8

iconv -f GB2312 -t UTF-8 foo.txt > foo3.txt

4. UTF-8 → GB2312

iconv -f UTF-8 -t GB2312 foo.txt > foo4.txt

批次轉換腳本

情境:目前目錄下所有 *.txt 為 GB2312,需全數轉為 BIG5,副檔名加 .big5

#!/bin/bash
# 檔名:gb2312_to_big5.sh
for file in *.txt; do
  if [[ -f "$file" ]]; then
    iconv -f GB2312 -t BIG5 "$file" > "${file}.big5"
    echo "Converted: $file -> ${file}.big5"
  fi
done

執行:

chmod +x gb2312_to_big5.sh
./gb2312_to_big5.sh

進階:遞迴處理子目錄、保留目錄結構、錯誤處理

#!/bin/bash
# 遞迴轉換,輸出至對應目錄下的 converted/ 資料夾
SRC_ENC="GB2312"
DST_ENC="BIG5"
find . -type f -name "*.txt" | while IFS= read -r file; do
  outdir="converted/$(dirname "$file")"
  mkdir -p "$outdir"
  outfile="$outdir/$(basename "$file")"
  if iconv -f "$SRC_ENC" -t "$DST_ENC" "$file" > "$outfile" 2>/dev/null; then
    echo "OK: $file"
  else
    echo "FAIL: $file" >&2
  fi
done

常見問題與技巧

  • 編碼偵測:若不確定來源編碼,可用 file -i filename 或 enca filename(需安裝)輔助判斷。
  • BOM 處理:UTF-8 帶 BOM 可能導致腳本錯誤,轉換後可用 sed -i '1s/^\xEF\xBB\xBF//' 移除。
  • 不可轉換字元:預設遇到無法轉換的字元會報錯停止。加入 -c 參數自動略過:iconv -c -f GB2312 -t UTF-8 ...
  • //TRANSLIT 近似轉換:目標編碼無對應字元時嘗試近似字元(如重音字母轉純字母):iconv -f UTF-8 -t ASCII//TRANSLIT ...
  • 大檔案效能:iconv 為串流處理,記憶體佔用極低,適合 GB 級大檔。

替代工具

  • enca:自動偵測並轉換編碼(enca -L zh_CN -x UTF-8 *.txt)
  • convmv:檔案名稱編碼轉換(而非內容)
  • 編輯器:Vim (:set fileencoding=utf-8)、VS Code(右下角編碼切換)
Copyright © Windows教程網 All Rights Reserved