How can I count the number of lines of a file with common tools?

I am redirecting grep results to a file, and then using cat to show its contents on the screen. I want to know how many lines of results I have in my results file and then add it to some counter.

What will be the best way? Any relevant flag to grep or cat?

Asked By: k-man



your_command | wc -l

From the manual:

       wc - print newline, word, and byte counts for each file


       -l, --lines
          print the newline counts
Answered By: aioobe

You can use wc -l to get line count.


$ cat foobar.txt | wc -l
Answered By: Steven Bakhtiari

The -c flag will do the job. For example:

 grep -c ^ filename

will count the lines returned by grep.

Documented in the man page:

-c, –count
Suppress normal output; instead print a count of matching lines for each input file

Answered By: peri4n

If you have already collected the grep output in a file, you could output a numbered list with:

cat -n myfile

If you only want the number of lines, simply do:

wc -l myfile

There is absolutely no reason to do:

cat myfile | wc -l

…as this needlessly does I/O (the cat) that wc has to repeat. Besides, you have two processes where one suffices.

If you want to grep to your terminal and print a count of the matches at the end, you can do:

grep whatever myfile | tee /dev/tty | wc -l

Note: /dev/tty is the controlling terminal. From the tty(4) man page:

The file /dev/tty is a character file with major number 5 and minor number 0, usually of mode 0666 and root.tty. It is a synonym for the controlling terminal of a process, if any.

In addition to the ioctl(2) requests supported by the device that tty refers to, the ioctl(2) request TIOCNOTTY is supported.

Answered By: JRFerguson

Don’t use wc: it doesn’t count the last line if it’s not terminated by the end of line symbol (at least on mac).
Use this instead:

nbLines=$(cat -n file.txt | tail -n 1 | cut -f1 | xargs)
Answered By: ling

Using AWK to count the lines in a file

awk 'END {print NR}' filename
Answered By: Vivek parikh
Categories: Answers Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.