Wc -l does NOT count the last file if it does not have an end-of-line character

I need to count all lines of a unix file. The file has 3 lines, but wc -l only gives 2 accounts.

I understand that it does not count the last line, because it does not have a line terminator

Can someone tell me how to read this line?

+6
source share
3 answers

It is better to have all lines ending in EOL \n in Unix files. You can do:

 { cat file; echo ''; } | wc -l 

Or this awk:

 awk 'END{print NR}' file 
+6
source

grep -c returns the number of matching lines. Just use the empty string "" as the appropriate expression:

 $ echo -n $'a\nb\nc' > 2or3.txt $ cat 2or3.txt | wc -l 2 $ grep -c "" 2or3.txt 3 
+6
source

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.

+3
source

Source: https://habr.com/ru/post/981249/


All Articles