wc -l给出了错误的结果

nov*_*cik 16 bash wc

我从wc -l命令得到了错误的结果.经过很长时间:(检查发现问题的核心,这里是模拟:

$ echo "line with end" > file
$ echo -n "line without end" >>file
$ wc -l file
       1 file
Run Code Online (Sandbox Code Playgroud)

这是两行,但缺少最后一行"\n".任何简单的方案?

jm6*_*666 19

对于该wc行,以"\n"字符结尾.其中一个解决方案就是利用线条.grep没有寻找结束NL.

例如

$ grep -c . file        #count the occurrence of any character
2
Run Code Online (Sandbox Code Playgroud)

以上不会算空行.如果你想要它们,请使用

$ grep -c '^' file      #count the beginnings of the lines
2
Run Code Online (Sandbox Code Playgroud)


Bil*_*ill 14

来自男人的页面 wc

 -l, --lines
              print the newline counts
Run Code Online (Sandbox Code Playgroud)

形成手册页 echo

 -n     do not output the trailing newline
Run Code Online (Sandbox Code Playgroud)

所以你有1 newline你的文件,因此wc -l显示1.

您可以使用以下awk命令来计算行数

 awk 'END{print NR}' file
Run Code Online (Sandbox Code Playgroud)