我知道我可以使用以下命令在OSX下转换单个文件编码:
iconv -f ISO-8859-1 -t UTF-8 myfilename.xxx > myfilename-utf8.xxx
我必须转换一堆具有特定扩展名的文件, 所以我想将文件编码从ISO-8859-1转换为UTF-8 对于文件夹/ mydisk / myfolder中的所有* .ext文件
也许有人知道如何做到这一点的语法
感谢
EKKE
答案 0 :(得分:25)
亚当的评论告诉我如何解决它, 但这是我使其工作的唯一语法:
find /mydisk/myfolder -name \*.xxx -type f | \
(while read file; do
iconv -f ISO-8859-1 -t UTF-8 "$file" > "${file%.xxx}-utf8.xxx";
done);
-i ... -o ...不起作用,但是>
再次EKKE
答案 1 :(得分:3)
如果你的shell是bash,就像这样
for files in /mydisk/myfolder/*.xxx
do
iconv -f ISO-8859-1 -t UTF-8 "$files" "${files%.xxx}-utf8.xxx"
done
答案 2 :(得分:2)
这是在mac 10.10中测试的示例。 按名称查找文件,转换编码,然后替换原始文件。完美。 感谢Roman Truba的示例,将下面的完整代码复制到shell脚本中。
#!/bin/bash
find ./ -name *.java -type f | \
(while read file;
do if [[ "$file" != *.DS_Store* ]]; then
if [[ "$file" != *-utf8* ]]; then
iconv -f ISO-8859-1 -t UTF-8 "$file" > "$file-utf8";
rm $file;
echo mv "$file-utf8" "$file";
mv "$file-utf8" "$file";
fi
fi
done);
答案 3 :(得分:1)
试试这个......经过测试和工作:
第一步(ICONV): find / var / www / -name * .php -type f | (当读取文件时;执行iconv -f ISO-8859-2 -t UTF-8“$ file”>“$ {file%.php} .phpnew”; done)
第二步(REWRITE - MV):
find / var / www / -name“* .phpnew”-type f | (读取文件时;执行mv $ file echo $file | sed 's/\(.*\.\)phpnew/\1php/'
;完成)
这只是我研究的结论:)
希望它有所帮助 Jakub Rulec
答案 4 :(得分:0)
您可以使用任何脚本语言编写脚本来迭代/ mydisk / myfolder中的每个文件,使用正则表达式[。(。*)$]检查扩展名,如果是“ext”,则运行以下命令(或来自系统调用。
“iconv -f ISO-8859-1 -t UTF-8”+ file.getName()+“>” + file.getName()+“ - utf8.xxx”
这只是Python中的几行,但我把它作为练习留给读者来完成查找目录迭代和正则表达式的细节。
答案 5 :(得分:0)
如果您想以递归方式执行此操作,可以使用find(1)
:
find /mydisk/myfolder -name \*.xxx -type f | \
(while read file; do
iconv -f ISO-8859-1 -t UTF-8 -i "$file" -o "${file%.xxx}-utf8.xxx
done)
请注意,由于我们需要对文件名进行操作,即切断,我使用| while read
而不是-exec
选项查找(或管道到xargs
)关闭.xxx
扩展程序(使用${file%.xxx}
)并添加-utf8.xxx
。
答案 6 :(得分:0)
我延伸了Albert.Qings剧本:
为目录和文件名模式添加了一个参数
#!/bin/bash
command=${1-"usage"}
searchPattern=${2-"*.java"}
searchDirectory=${3-"."}
if [[ "$command" == "usage" ]]; then
echo "convert-file-to-utf8.sh [usage|dry|exec] [searchPattern=$searchPattern] [searchDirectory=$searchDirectory]"
exit
fi
find $searchDirectory -type f -name "$searchPattern" | \
(while read file;
do if [[ "$file" != *.DS_Store* ]]; then
if [[ "$file" != *-utf8* ]]; then
currentEncoding="$(file --brief --mime-encoding $file)"
if [[ "$currentEncoding" != "utf-8" ]]; then
echo "command:$command / iconv -f $currentEncoding -t UTF-8 $file"
if [[ "$command" == "exec" ]]; then
iconv -f $currentEncoding -t UTF-8 "$file" > "$file-utf8";
rm $file;
echo mv "$file-utf8" "$file";
mv "$file-utf8" "$file";
fi
fi
fi
fi
done);
在MacOS X 10.12.6 / Sierra上进行测试。