为什么grep不能查找UTF-16编码的文件呢?

264 views
Skip to first unread message

leftuestc

unread,
Apr 16, 2011, 7:30:41 AM4/16/11
to Shanghai Linux User Group
用vim打开可以显示正常的内容,但是cat,tail这些就是乱码。用file看了一下,结果是Little-endian UTF-16
Unicode character data, with CRLF line terminators
然后在这片帖子里找到了解决方案,http://cybergav.in/tag/little-endian-utf-16-unicode-
english-character-data/
就开始用 iconv -f UTF-16 -t UTF-8 filename |grep pattern
然后就得到了 Binary file (standard input) matches的提示,
再查,是因为grep认定输出结果是二进制文件,加上-a选项就可以了
然后就 iconv -f UTF-16 -t UTF-8 filename |grep -a pattern

问题是我用iconv转换过文件编码格式了,再看文件类型,还是Little-endian UTF-16 Unicode character
data, with CRLF line terminators
...
我现在都不知道这到底是什么文件了,UTF-16的文本文件还是2进制文件啊?
说下想解决的东西,就是目录底下有一堆这样的文件,有些文件里有我想找的内容,目的就是找出哪些文件有这些内容。能把文件名保存到一个输出文件里。

OceanBoo

unread,
Apr 16, 2011, 8:21:50 AM4/16/11
to sh...@googlegroups.com
2011/4/16 leftuestc <lizhe...@gmail.com>:

> 问题是我用iconv转换过文件编码格式了,再看文件类型,还是Little-endian UTF-16 Unicode character

你转换不会就是用 iconv -f UTF-16 -t UTF-8 filename 吧?

--
Thanks & Best Regards,
OceanBoo From ShenZhen,China

Daniel Qian

unread,
Apr 16, 2011, 8:34:29 AM4/16/11
to sh...@googlegroups.com
iconf -f UTF-16 -t UTF-8 filename 只是输出结果到stdout,如果要保存文件还是需要加上 -o 参数的

Yongwei Wu

unread,
Apr 16, 2011, 9:09:11 PM4/16/11
to sh...@googlegroups.com
你没有试过iconv -f utf-16 -t utf-8直接检查输出结果吧?Little-endian的话,你应当使用utf-16le而不是utf-16。

2011/4/16 leftuestc <lizhe...@gmail.com>:

--
Wu Yongwei
URL: http://wyw.dcweb.cn/

Zhang Weiwu, Beijing

unread,
Apr 17, 2011, 6:17:32 AM4/17/11
to sh...@googlegroups.com
On 04/16/2011 07:30 PM, leftuestc wrote:
> 问题是我用iconv转换过文件编码格式了,再看文件类型,还是Little-endian UTF-16 Unicode

很可能这个文件来自Windows的“保存为unicode”。这种文件有BOM,除了用iconv还
得去掉BOM才行。

BOM的概念用google找一下吧。

--
我的博客:
http://zhangweiwu.ixiezi.com/
网站进化论 --写给需要网站或后悔有了网站的人

leftuestc

unread,
Apr 17, 2011, 12:18:16 PM4/17/11
to Shanghai Linux User Group
事实上,是摩托罗拉的手机短信导出保存的文件。
很奇怪,不是纯文本文件,因为grep的时候提示Binary file

On 4月17日, 下午6时17分, "Zhang Weiwu, Beijing" <zhangwe...@realss.com>
wrote:

Zhang Weiwu, Beijing

unread,
Apr 18, 2011, 12:35:45 AM4/18/11
to sh...@googlegroups.com
On 04/18/2011 12:18 AM, leftuestc wrote:
> 很奇怪,不是纯文本文件,因为grep的时候提示Binary file

说明你没有按我说的上网去搜索BOM嘛。这里看来只好在贴子里说清楚BOM了。如下:

有BOM都会grep提示BINARY。BOM不是文本,是不可见字符构成的文本头,这些
不可见字符是终端上看不到的。 这些字符iconv不能转换,但是定义了后面的
是什么encoding。

August

unread,
Apr 19, 2011, 2:17:07 AM4/19/11
to sh...@googlegroups.com
grep 也可以搜bin 文件啊,加-a 参数,按照ASCII 来搜

2011/4/18 Zhang Weiwu, Beijing <zhang...@realss.com>:

--
Best Regards
August

Reply all
Reply to author
Forward
0 new messages