bash wc -l 给出错误的结果
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16533748/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
The wc -l gives wrong result
提问by novacik
I got wrong result from the wc -lcommand. After a long :( checking a found the core of the problem, here is the simulation:
我从wc -l命令中得到了错误的结果。看了好久:(查了下发现问题的核心,下面是模拟:
$ echo "line with end" > file
$ echo -n "line without end" >>file
$ wc -l file
1 file
here are two lines, but missing the last "\n". Any easy solution?
这里有两行,但缺少最后一个“\n”。有什么简单的解决办法吗?
回答by jm666
For the wcline is what ends with the "\n" char. One of solutions is grep-ing the lines. The grep not looking for the ending NL.
因为该wc行是以“\n”字符结尾的。解决方案之一是 grep-ing 行。grep 不寻找结尾 NL。
e.g.
例如
$ grep -c . file #count the occurrence of any character
2
the above will not count empty lines. If you want them, use the
以上不会计算空行。如果你想要它们,请使用
$ grep -c '^' file #count the beginnings of the lines
2
回答by Bill
from man page of wc
从手册页 wc
-l, --lines
print the newline counts
form man page of echo
表单手册页 echo
-n do not output the trailing newline
so you have 1newlinein your file and thus wc -lshows 1.
所以你1newline在你的文件中,因此wc -l显示1.
You can use the following awkcommand to count lines
您可以使用以下awk命令来计算行数
awk 'END{print NR}' file

