linux递归批量转化文件编码gb2312 to utf-8

发表于

#!/bin/bash
# 设置源目录
SOURCE_DIR="./"
# 查找并转换文件
find "$SOURCE_DIR" -type f -name "*.php" -exec bash -c '
for file; do
# 创建临时文件
temp_file="$(mktemp)"
# 使用 iconv 转换文件编码,GBK 到 UTF-8
iconv -f GB2312 -t UTF-8 "$file" > "$temp_file" &&
# 检查转换是否成功,成功后替换原文件
if [ $? -eq 0 ]; then
mv "$temp_file" "$file"
echo "Converted $file to UTF-8"
else
echo "Failed to convert $file"
rm -f "$temp_file"
fi
done
' bash {} +
echo "All files have been processed."