如何批量将旧文件转换为UTF8?

如何批量将旧文件转换为UTF8?

我认为对我来说理想的解决方案是对选定文件执行编码转换的 Nautilus 脚本

以下脚本读取选定文件的编码,如果不是 utf8,则执行 utf8 转换,但我无法弄清楚如何让它处理多个文件

CHARSET="$(file -bi "$1"|awk -F "=" '{print $2}')"
if [ "$CHARSET" != utf-8 ]; then
iconv -f "$CHARSET" -t utf8 "$1" -c -o "$1.utf8"
fi

答案1

假设你的脚本名为convert-to-utf-8.sh。下面介绍如何使其在多个文件中运行:

for filename in file1 file2 file3 ; do ./convert-to-utf-8.sh "$filename" ; done

您可以将该 for 循环合并到脚本本身中,如下所示:

for filename in "$@"; do
    CHARSET="$(file -bi "$filename"|awk -F "=" '{print $2}')"
    if [ "$CHARSET" != utf-8 ]; then
        iconv -f "$CHARSET" -t utf8 "$filename" -c -o "$filename.utf8"
    fi
done

然后,您可以使用多个文件名运行该脚本,如下所示:

./convert-to-utf-8.sh file1 file2 file3

答案2

这是一个简单又好鹦鹉螺脚本感谢弗利姆如上面的答案所示:

#!/bin/sh
#Nautilus Script to determine encoding of selected file(s) and convert to utf8 if necessary
#
for filename in $@; do
    CHARSET="$(file -bi "$filename"|awk -F "=" '{print $2}')"
    if [ "$CHARSET" != utf-8 ]; then
        iconv -f "$CHARSET" -t utf8 "$filename" -c -o "$filename.utf8" &&
        mv -f "$filename.utf8" "$filename"
    fi
done

相关内容