The wc -l gives wrong result

novacik picture novacik · May 14, 2013 · Viewed 12.1k times · Source

I got wrong result from the wc -l command. After a long :( checking a found the core of the problem, here is the simulation:

$ 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?

Answer

jm666 picture jm666 · May 14, 2013

For the wc line is what ends with the "\n" char. One of solutions is grep-ing the lines. The grep not looking for the ending 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