Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The wc -l gives wrong result

Tags:

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?

like image 582
novacik Avatar asked May 14 '13 01:05

novacik


People also ask

What is WC in bash?

wc stands for Word Count, although it can also count characters and lines. This makes it a flexible tool for counting any kind of items. It is most commonly used to count the number of lines in a file, or (as with most Unix tools) in any other data sent to it, but it can count characters and words, too.

Who WC Linux?

-L: The 'wc' command allow an argument -L, it can be used to print out the length of longest (number of characters) line in a file. So, we have the longest character line Arunachal Pradesh in a file state. txt and Hyderabad in the file capital.


2 Answers

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
like image 55
jm666 Avatar answered Oct 12 '22 14:10

jm666


from man page of wc

 -l, --lines
              print the newline counts

form man page of echo

 -n     do not output the trailing newline

so you have 1 newline in your file and thus wc -l shows 1.

You can use the following awk command to count lines

 awk 'END{print NR}' file
like image 43
Bill Avatar answered Oct 12 '22 16:10

Bill