ubuntu utf-8转换器脚本



我有一个脚本,它可以与iconv一起使用,自动将目录中一组文件的编码转换为UTF-8,并将原始文件的扩展名更改为.old,但我想知道如何更改脚本,使其看起来并转换目录中的所有文件和所有子目录中的全部文件。

终端代码:

sudo convert/dir_iconv.sh convert/books cp1251 utf8

dir_iconv.sh脚本

#!/bin/bash
ICONVBIN='/usr/bin/iconv' # path to iconv binary
if [ $# -lt 3 ]
then
echo "$0 dir from_charset to_charset"
exit
fi
for f in $1/*
do
if test -f $f
then
echo -e "nConverting $f"
/bin/mv $f $f.old
$ICONVBIN -f $2 -t $3 $f.old > $f
else
echo -e "nSkipping $f - not a regular file";
fi
done

不要使用for f in $1/*,而是尝试使用类似for f in $(find $1 -type f)的东西。此外,find命令上的-type f选项将跳过非文件对象,因此不需要test和条件逻辑。

[编辑]

例如,这可能会起作用,完全未经测试(也清理了一些格式化):

#!/bin/bash
ICONVBIN='/usr/bin/iconv' # path to iconv binary
if [[ $# -lt 3 ]]; then
    echo "$0 dir from_charset to_charset"
    exit
fi
for f in $(find $1 -type f); do
    echo "Converting $f"
    /bin/mv $f $f.old
    $ICONVBIN -f $2 -t $3 $f.old > $f
done

如果iconv不能像你预期的那样工作,vim也可以完成任务:

for f in *.*; do vim -c "set fileencoding=utf8|wq" $f; done

最新更新