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
?
Use
your_command | wc -l
From the manual:
NAME
wc - print newline, word, and byte counts for each file
...
-l, --lines
print the newline counts
You can use wc -l to get line count.
Example:
$ cat foobar.txt | wc -l
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
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 andowner.group
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, theioctl(2)
requestTIOCNOTTY
is supported.
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)
Using AWK to count the lines in a file
awk 'END {print NR}' filename