会用Linux的人都知道用wc -l 可以统计文本文件的行数。
但是如下的例子,好像统计的就不对:
pp@dell:~/tmp$ printf bla > file
pp@dell:~/tmp$ wc -l file
0 file
通过man wc我们可以看到:
-l 的意思是统计 '\n'的数量,上面的例子file中没有换行符,自然统计出来的结果是0
-l, --lines
print the newline counts
那么,怎么才能统计出正确的行数呢?
答案是用grep -c "" ,如下:
pp@dell$ grep -c "" file
1
那么大名鼎鼎的wc -l不能用了???
wc可以Unix系的基础工具呀,这统计的行数不正确属于重大bug呀!!!
wc的设计者也太垃圾了吧。
No, No, No
事出反常必有妖,这个锅并不是wc的。
POSIX 标准里面定义一行用的就是 一段文字以newline结尾,如果不按这个标准来就不认为这是一行文本。
POSIX, this is a set of standards specified by IEEE to maintain compatibility between operating systems.
One of which is the definition of a "line" being a sequence of zero or more non- characters plus a terminating newline character.
在unix系统中newline就是'\n'
在windows系统中newline 是'\r\n'
但是实际上有些时候大家没有严格按照POSIX的标准来。
参考:
newlines - What's the point in adding a new line to the end of a file? - Unix & Linux Stack Exchange