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 檔案字元編碼轉換實戰:convmv 批次修正檔名、iconv 轉換檔案內容、Vim 即時另存編碼

編輯:關於 Linux

Windows (GBK/Big5) 與 Linux (UTF-8) 編碼不一致導致檔名亂碼、內容無法閱讀。本文提供三層解決方案:convmv 批次修正檔名編碼、iconv 轉換檔案內容編碼、Vim 開啟時指定/另存編碼。

場景 1:檔名亂碼 (目錄/檔案名稱)

Windows 上傳的檔案在 Linux 顯示為 ???.txt 或亂碼。

# 安裝
yum install -y convmv   # CentOS/RHEL (EPEL)
apt install -y convmv   # Debian/Ubuntu

# 預覽 (不實際修改)
convmv -f GBK -t UTF-8 -r /path/to/files

# 確認無誤後執行 (加 --notest)
convmv -f GBK -t UTF-8 -r --notest /path/to/files

# 常見來源編碼: GBK (簡體)、Big5 (繁體)、CP936、GB2312、CP950

參數:-r 遞迴、--notest 實際重命名、--lower/--upper 大小寫轉換。

場景 2:檔案內容編碼轉換

# iconv 基本語法
iconv -f FROM_ENCODING -t TO_ENCODING inputfile -o outputfile

# 範例: GBK → UTF-8
iconv -f GBK -t UTF-8 gbk_file.txt -o utf8_file.txt

# 批次轉換 (保留原檔備份)
for f in *.txt; do
    iconv -f GBK -t UTF-8 "$f" -o "${f%.txt}_utf8.txt"
done

# 檢測檔案編碼 (需安裝 enca 或 file)
file -i *.txt
enca -L zh_CN *.txt

場景 3:Vim 即時編碼處理

" 開啟時指定編碼 (若自動偵測失敗)
:e ++enc=GBK %

" 另存為 UTF-8
:set fileencoding=utf-8
:w

" 另存為 GBK
:set fileencoding=gbk
:w

" 設定預設編碼 (放入 ~/.vimrc)
set encoding=utf-8
set fileencodings=utf-8,gbk,big5,latin1

進階:腳本化雙向轉換

#!/bin/bash
# 轉換目錄下所有 .txt .csv .log 從 GBK → UTF-8
find /data -type f \( -name "*.txt" -o -name "*.csv" -o -name "*.log" \) | while IFS= read -r f; do
    # 偵測編碼 (簡易: 檢查是否含中文高位元組)
    if file "$f" | grep -q "ISO-8859"; then  # 常被誤判為 ISO-8859
        echo "轉換: $f"
        iconv -f GBK -t UTF-8 "$f" -o "$f.new" && mv "$f.new" "$f"
    fi
done

FTP/SFTP 客戶端編碼設定

  • FileZilla:站點管理 → 字元集 → 強制 UTF-8 (或 GBK)。
  • WinSCP:環境 → 字元集 → UTF-8。
  • lftp:set ftp:charset GBK / set ftp:charset UTF-8。

常見問題

  • iconv: illegal input sequence at position N:來源編碼判斷錯誤,嘗試 -c 忽略非法序列或用 enca 精確偵測。
  • 檔名轉換後仍亂碼:檔案系統不支援 UTF-8 (極舊 ext2/fat32 掛載參數錯誤),檢查 mount 選項 iocharset=utf8。
  • 大量檔案轉換效能:iconv 單執行緒,可用 parallel 或 xargs -P 平行化。
  • 依據層級 (檔名/內容/編輯器) 選擇工具,徹底解決跨平台中文編碼亂碼困擾。

    Copyright © Windows教程網 All Rights Reserved