Windows (GBK/Big5) 與 Linux (UTF-8) 編碼不一致導致檔名亂碼、內容無法閱讀。本文提供三層解決方案:convmv 批次修正檔名編碼、iconv 轉換檔案內容編碼、Vim 開啟時指定/另存編碼。
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 大小寫轉換。
# 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
" 開啟時指定編碼 (若自動偵測失敗)
: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
set ftp:charset GBK / set ftp:charset UTF-8。iconv: illegal input sequence at position N:來源編碼判斷錯誤,嘗試 -c 忽略非法序列或用 enca 精確偵測。mount 選項 iocharset=utf8。iconv 單執行緒,可用 parallel 或 xargs -P 平行化。依據層級 (檔名/內容/編輯器) 選擇工具,徹底解決跨平台中文編碼亂碼困擾。