If your file doesn't ends with a \n
(new line) the wc -l
gives a wrong result. Try it with the next simulated example:
echo "line1" > testfile #correct line with a \n at the end
echo -n "line2" >> testfile #added another line - but without the \n
the
$ wc -l < testfile
1
returns 1. (The wc
counts the number of newlines (\n
) in a file.)
Therefore, for counting lines (and not the \n
characters) in a file, you should to use
grep -c '' testfile
e.g. find empty character in a file (this is true for every line) and count the occurences -c
. For the above testfile
it returns the correct 2.
Additionally, if you want count the non-empty lines, you can do it with
grep -c '.' file
Don't trust wc
:)
Ps: one of the strangest use of wc
is
grep 'pattern' file | wc -l
instead of
grep -c 'pattern' file