Linux Commands

How to Count Lines in a File in Linux

It gets really important to know the exact number of lines that these files span when you are working with very large files. You can do this by making use of different methods. Therefore, in this article, we shared with you some of the methods of counting the lines in a file on a Linux Mint 21 system.

Ways of Counting the Lines in a File in Linux Mint 21:

There are multiple ways of counting the lines of a file in Linux Mint 21. However, we are going to discuss the five most commonly used methods. Before moving on to these methods, we will share the contents of the file whose lines we wish to find. To display the contents of this file on the terminal, we will use the following command:

$ cat testfile.txt

The contents of our test file are shown in the image below:

From here, you can see that this file consists of 3 lines in total. You will be able to re-verify this in all the methods that we are going to discuss.

Method # 1: The “wc” Command

The “wc” command can be used to count the total number of lines in a file in the following manner:

$ wc –l testfile.txt

The output of this command shown in the image below confirms that the number of lines of our file is “3”.

Method # 2: The “awk” Command

Now, we will use the “awk” command to print the number of lines of a file in the following way:

$ awk ‘END{print NR}’ testfile.txt

The number of lines of our specified file is shown in the image below:

Method # 3: The “sed” Command

The “sed” command can also be used to display the number of lines in a file in the following way:

$ sed –n ‘$=’ testfile.txt

The number of lines of our specified file is shown in the image below:

Method # 4: The “grep” Command

To use the “grep” command for counting the lines of a file, we will run it in the following manner:

$ grep –c “.*’ testfile.txt

The total number of lines of our file can be verified from the image shown below:

Method # 5: The “nl” Command

Finally, we will use the “nl” command to print the number of lines of our file by executing it in the following way:

$ nl testfile.txt | tail -1 | awk ‘{print $1}’

You can confirm from the image shown below that the total number of lines in our file is “3”.

Conclusion

In this guide, we shared with you five very simple methods of counting the lines in a file in Linux Mint 21. You can especially make use of these methods when you have extremely large files and it is nearly impossible for you to count the total number of lines of these files manually.

Similar Posts