Different command methods to count the total lines in a file

In this article, we will see different methods to get the count of the total lines in a file.

1. Use the combination of wc and cat

This is the simplest method, a piping of cat and wc
 cat file | wc -l  

2. Use grep

grep has the '-c' option to count lines when some patterns are matched. To get the pattern of every line, we will use '.*', which means to match anything.
 grep -c '.*' file  

3. Use sed

The sed command uses the '=' operator for line numbering. The '$' tells to give the count only for the last line.
 sed -n '$=' file  

4. Use awk

With awek, we can use the NR variable to get the lines count. NR contains the line number and by printing NR at the end block, we get the line number of the last line, which is exactly what we need:
 awk 'END {print NR}' file  

5. Use perl

Similar to awk, perl also uses the END block. But instead of NR, perl uses $ to denote the line number.
 perl -lne 'END {print $.}' file  
linux tips and tricks