How to count the number of lines in a file?

Count Number Of Lines

There are numerous ways to count the number of lines in a file in Linux. We’ll go over some of the quickest ways to achieve this task and get the line count.

Ways to Count the Number of Lines in a File

Let’s start with the most common and move to some more uncommon but also useful methods of counting lines in Linux.

1. Using the wc command

The easiest way to count lines in Linux is with the use of the wc (word count) command. That’s because the command is created with the purpose of counting lines and words in files.

wc -l filename
Wc Command
using wc Command

2. Using the grep command

Grep filter searches a file for a particular pattern of characters and displays all lines that contain a specific pattern. Grep is short for global regular expression print.

grep --regexp="$" --count filename

‘$’ in regular expression is used for signifying the end of a line. –count is used to count the number of lines that match the pattern. This command matches end of line of prints the count.

Grep
using grep

3. Using the awk command

We recently covered the awk command in our previous tutorial. The number of records (NR) can be printed in the END section to get the number of lines in a Linux file.

awk 'END { print NR }' filename 
Using Awk Command
using awk command

4. Using the sed command

sed is a tool used for editing files. Sed is primarily used for replacing/deleting/ adding text to a file. However, it can also be used for counting the number of lines in a file.

sed -n $= filename
Using Sed Command to count the number of lines in a file
using sed command

5. Using a Perl Script to Count Lines

Perl officially stands for “Practical Extraction and Reporting Language”. Perl, much like bash is also a scripting language.

perl -lne 'END { print $. }' filename 
Using Perl Command
using perl command

6. Using while loop

While loop in shell scripts can also be used to count the number of lines. Using the while loop to count the number of lines in file will give a little ego boost to the programmer within you.

count=0
while read
do
  ((count=$count+1))
done <file.txt
echo $count
Using While Loop
using while loop

The loop reads standard input line by line and increases the variable count each time. Due to redirection (<file.txt after done), standard input for the loop is from file.txt

Conclusion

These are several ways to count the number of lines in a file in Linux. Using wc is the easiest and trivial way to achieve this. Another factor to consider is the time that each of these commands takes to count the number of lines. Time becomes an important aspect if the file is too voluminous and contains millions of lines. If you are interested in knowing about the performance of each command in terms of time taken, check this answer on StackOverflow