需求:把 /home/zichen/dxzs0305 目錄底下所有 PHP 檔的編碼從 UTF-8 轉成 GB2312。手動一個個改不現實,用 iconv 搭配 find 就能批次處理。
#!/bin/bash -x
SUBFIX="php" # 需要轉換的副檔名
cd /home/zichen/dxzs0305 # 目標根目錄
if [ -z $1 ]; then
cd $PWD
else
if [ -d $1 ]; then
cd $1
else
echo " $1 is not exist;"
exit 1
fi
fi
for i in $SUBFIX;
do
files=`find . -name "*.$i"`
for f in $files;
do
type=`file $f | awk -F':' '{print $2}' | awk '{print $1}'`
if [ $type != "ISO-8859" ]; then
iconv -f UTF-8 -t GB2312 -o $f $f
# 若改用 enca:enca -L UTF-8 -x zh_cn $f
# 需先安裝:sudo apt-get install enca
else
echo "$f encoding is :$type"
fi
done
done
流程說明:先用 file 搭配 awk 取出檔案編碼型態,若已是 ISO-8859(非 UTF-8 中文檔常見的判定)就跳過,否則用 iconv 原地轉換。
iconv 用於轉換檔案編碼,預設輸出到標準輸出,可用 -o 指定輸出檔。
-f, --from-code=名稱:原始編碼-t, --to-code=名稱:目標編碼-l, --list:列出所有已知字元集-c:輸出時忽略無效字元-o, --output=FILE:指定輸出檔-s, --silent:關閉警告;--verbose:印出進度-V, --version:版本資訊實務提醒:批次轉碼前務必先備份或用 git 留一份可回溯的版本,因為 -o 直接覆寫原檔,一旦編碼判斷錯誤就難以還原。