Take the 2-minute tour ×

I'm sure there are many ways to do this: how can I count the number of lines in a text file?

$ <cmd> file.txt
1020 lines
share|improve this question
add comment

3 Answers

up vote 20 down vote accepted

The standard way is with wc, which takes arguments to specify what it should count (bytes, chars, words, etc.); -l is for lines:

$ wc -l file.txt
1020 file.txt
share|improve this answer
How do I count the lines in a file if I want to ignore comments? Specifically, I want to not count lines that begin with a +, some white space (could be no white space) and then a %, which is the way comment lines appear in a git diff of a MATLAB file. I tried doing this with grep, but couldn't figure out the correct regular expression. –  Gdalya Jul 11 '13 at 1:36
@Gdalya I hope the following pipeline will do this (no tests were perfomed): cat matlab.git.diff | sed -e '/^\+[ ]*.*\%$/d' | wc -l. /regexp/d deletes a line if it matches regexp, and -e turns on an adequate (IMNSHO) syntax for regexp. –  dbanet Nov 6 '13 at 21:29
add comment

As Michael said, wc -l is the way to go. But, just in case you inexplicably have bash, perl, or awk but not wc, here are a few more solutions:


$ LINECT=0; while read -r LINE; do (( LINECT++ )); done < file.txt; echo $LINECT

Perl Solutions

$ perl -lne 'END { print $. }' file.txt

and the far less readable:

$ perl -lne '}{ print $.' file.txt

Awk Solution

$  awk 'END {print NR}' file.txt
share|improve this answer
add comment

Steven D forgot GNU sed:

sed -n $= file.txt

Also, if you want the count without outputting the filename and you're using wc:

wc -l < file.txt

Just for the heck of it:

cat -n file.txt | tail -n 1 | cut -f1
share|improve this answer
Or grep -c '', or tr -dc '\n' | wc -c, or nl -ba -nln | tail -n 1 |sed -e 's/[^0-9].*//'... Is any of these useful in itself (as opposed to things to build upon to make a program that does more than counting lines), other than wc -l and pure (ba)sh? –  Gilles Dec 3 '10 at 1:58
+1. Small note: cat -n is a GNU extension. –  Steven D Dec 3 '10 at 2:03
@Gilles: I think the phrase "many ways" in the question triggered a challenge that Steve and I rose to. –  Dennis Williamson Dec 3 '10 at 2:03
@Gilles: sed 's/.*//' file.txt | uniq -c –  Dennis Williamson Dec 3 '10 at 2:30
@Gilles: Oh, you meant first. uniq -c -w 0 file.txt and you can cut -c -7 to keep only the number. Or, more POSIXly: uniq -c file.txt | awk '{c+=$1}END{print c}'. How about dc (even though it's not POSIX)? uniq -c file.txt | cut -c -7 | sed '$alax' | dc -e '[pq]sb[+z1=blax]sa' -. bc is POSIX: uniq -c file.txt | cut -c -7 | sed -n ':a;${s/\n/ + /gp;b};N;ba' | bc. The easy answer if you assume a limited line length: uniq -c -f 100000 file.txt. –  Dennis Williamson Dec 3 '10 at 16:21
show 6 more comments

Your Answer


