This approach will give the correct line count regardless of whether the last line in the file ends with a new line or not.
awk will make sure that every line output will end with a new line character. So that each line ends with a newline before sending the line to wc , use:
awk '1' file | wc -l
Here we use the trivial awk program consisting solely of the number 1 . awk interprets this cryptic statement as meaning "print a line", which he makes, being sure that there is a finite new line.
Examples
Create a file with three lines, each of which ends with a newline, and count the lines:
$ echo -n $'a\nb\nc\n' >file $ awk '1' f | wc -l 3
found the correct number.
Now try again with no last new line:
$ echo -n $'a\nb\nc' >file $ awk '1' f | wc -l 3
It still contains the correct number. awk automatically corrects the missing newline, but leaves the file alone if the last line of the newline is present.
source share