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

Ubuntu 查看與批量轉換檔案編碼:enca 工具與 Shell 腳本實戰

編輯:關於 Linux

Windows 預設編碼 GBK/GB2312,檔案移至 Linux 常出現亂碼。本文介紹 enca 查看編碼、單檔轉換,並提供遞迴批量轉換腳本。

安裝 enca

sudo apt-get install enca

常用指令

  • enca -L zh_CN 檔案:查看編碼
  • enca -L zh_CN -x UTF-8 檔案:就地轉碼為 UTF-8
  • enca -L zh_CN -x UTF-8 < 檔案1 > 檔案2:另存新檔不覆蓋原檔

批量轉換腳本 (encoding.sh)

#!/bin/bash
# 將指定目錄下檔案編碼遞迴轉為 UTF-8
function change_file_encoding() {
  for file in $(ls -l | awk '{print $9}'); do
    if [[ -d "$file" && $1 = "y" ]]; then
      cd "$file"; echo "$file"; change_file_encoding "$1"; cd ..
    elif [[ -f "$file" ]]; then
      echo "$file"; enca -L zh_CN -x UTF-8 "$file"
    fi
  done
}
read -p "please enter the dir path: " path
if [[ ! -x "$path" ]]; then echo "dir path not exists"; exit; fi
read -p "please enter if you want to recursive? y/n: " recur
cd "$path"
if [[ $recur = "y" ]]; then change_file_encoding "y"; else change_file_encoding "n"; fi

使用方式:chmod +x encoding.sh && ./encoding.sh,依提示輸入路徑與是否遞迴。

解決跨平台編碼亂碼,從單檔到批量一次搞定。

Copyright © Windows教程網 All Rights Reserved