Sometimes you may be required to count total lines in a file in Unix/Linux systems. This tutorial helps you with multiple methods to count the number of lines in a file in a Linux system via the command line.

Advertisement

Count lines with wc Command

The wc command is the “word counter” for the Unix/Linux systems. This is a widely used command among Linux users for counting the lines in a file. It is also useful for counting words and characters in a file.

Open a terminal and type command to count lines:

wc -l myfile.txt 

You can also count the number of lines on piped output.

cat myfile.txt | wc -l  

Using grep Command

Grep is another frequently used Linux command used for searching content with regular expressions. You can also use the grep command to count the number of lines in a file.

grep -c ".*" myfile.txt  

Using sed Command

The sed is known as stream editor for Unix/Linux systems. Mainly it is used for search and replace content from a file or a stream.

Use the sed command to count number of lines in a file:

sed -n '$=' myfile.txt  

Using awk Command

AWK is a useful data processing and reporting tool. It is default available on all major Linux distributions. You can also use awk for counting the number of lines from a file.

awk 'END{print NR}' myfile.txt  

Here NR keeps the number of the current input records.

Conclusion

This tutorial helped you to count lines in a file in the Linux system.

Share.

2 Comments

  1. I think you got a spelling mistake :

    “Please change (..) it will return number of files in file as output.”
    Shouldn’t it be “it will return number of lines in file as output?”

    Besides that, thanks for the article!

Leave A Reply

Exit mobile version