用尾部格式化错误

时间:2015-06-22 02:01:00

标签: linux bash unicode cygwin tail

如何通过tail正确解析此文件,而不会出现格式错误?

我在tail中使用cygwin来解析两个文件的最后十行。一个文件正确解析,另一个文件在每个字符之间包含一个空格。

$ tail file2.txt -n 4
22/06/2015 12:28 - Decompressing and saving profile extract...
22/06/2015 12:28 - Decompressing and saving profile extract...
22/06/2015 12:38 - Decompressing and saving profile extract...
22/06/2015 12:38 - Decompressing and saving profile extract...

$ tail file1.txt -n 4
P a c k a g e   s t a r t .
E l a p s e d   t i m e :   5 0 . 1 7 5 7 5 4 8   s e c s .
. . . P a c k a g e   E x e c u t e d .

R e s u l t :   S u c c e s s

当我在python中读取文件的原始内容时,我得到了以下内容,我认为这是一个unicode字符的负载

In [1]: open('file1.text', 'r').read()
Out[1]: '\xff\xfeP\x00a\x00c\x00k\x00a\x00g\x00e\x00 \x00s\x00t\x00a\x00r\x00t\x00.\x00\r\x00\n\x00E\x00l\x00a\x00p\x00s\x00e\x00d\x00 \x00t\x00i\x00m\x00e\x00:\x00 \x005\x000\x00.\x001\x007\x005\x007\x005\x004\x008\x00 \x00s\x00e\x00c\x00s\x00.\x00\r\x00\n\x00.\x00.\x00.\x00P\x00a\x00c\x00k\x00a\x00g\x00e\x00 \x00E\x00x\x00e\x00c\x00u\x00t\x00e\x00d\x00.\x00\r\x00\n\x00\r\x00\n\x00R\x00e\x00s\x00u\x00l\x00t\x00:\x00 \x00S\x00u\x00c\x00c\x00e\x00s\x00s\x00\r\x00\n\x00\r\x00\n\x00'
In [2]: print open('temp.txt', 'r').read()
■P a c k a g e   s t a r t .
E l a p s e d   t i m e :   5 0 . 1 7 5 7 5 4 8   s e c s .
. . . P a c k a g e   E x e c u t e d .

R e s u l t :   S u c c e s s

当我将file1.txt的全部内容复制到新文件test.txt时 - 问题不会再次发生。

$ tail test.txt
Package start.
Elapsed time: 50.1757548 secs.
...Package Executed.

Result: Success

文件似乎在每个字符和\x00之间都有字符\xff

1 个答案:

答案 0 :(得分:1)

该文件采用UTF-16格式,使用2个8位字节表示大多数字符(对于某些字符使用4个8位字节)。 128个ASCII字符中的每一个都表示为2个字节,一个零字节和一个包含实际字符值的字节。开始时的\xff\xfe序列是字节顺序标记(BOM);它表示是否先用高位或低位字节表示剩余的字符。

UTF-16是表示Unicode文本的几种方法之一。它最常用于Microsoft Windows。

我不确定为什么空字符显示为空格。这可能是由于您的终端仿真器的行为方式。

使用iconv命令将文件从UTF-16转换为其他格式。