我有一个bash脚本,它使用Perl的替换运算符替换指定目录中所有.htm文件中的字符串。
find $files_dir -name '*.htm' | while read line; do
ReplaceString "$line"
done
function ReplaceString {
perl -pi -e 's/string1/string2/g' "$1"
rm -rf "$1.bak"
}
问题是某些文件包含Unicode字符(例如'')。如果文件中存在任何Unicode字符,则不处理该文件,也不会发生字符串替换。当我从文件中删除Unicode时,字符串替换工作。
我正在寻找一种方法使我的程序“识别Unicode”,以便它可以处理任何文件,无论它是否包含Unicode。
我也尝试过使用sed而不是Perl:
sed -i 's/string1/string2/g' "$1"
给了我同样的问题。
非工作文件示例(已修剪):
<html>
<head><meta http-equiv=Content-Type content="text/html; charset=unicode"></head>
<style>
<!--
/* Font definitions (generated by MS Word) */
@list l0:level3
{mso-level-text:;}
-->
</style>
<body>
<p>string1</p>
</body>
</html>
答案 0 :(得分:0)
如池上和上午指出,.htm文件(使用Microsoft Word生成)以UTF-16le编码。 Perl替换操作不理解这种编码。
我通过使用MS Word以UTF-8编码保存非工作文件解决了这个问题。