Table of Contents
In this article we will show you how to Count Lines in file of Linux. In Unix/Linux platforms, you may need to count the number of lines in a file. This lesson shows you several ways to use the Linux command line to count the number of lines in a file. When the File parameter is set, the wc command prints both the file names and the desired counts. Most of the time, writers count the number of lines in a file to figure out how long their code or program is.
They do this to figure out how well the program works. A program with fewer lines that does the same job as a program with more lines is thought to work better. If you don’t give a file name for the File parameter, it only writes the total count to the standard output. On Linux, there are many ways to do the same thing. In the same way, you can use different tools to count the number of lines in a single file or in several files.
How to Count Lines in file of Linux
Using the wc command
- The one method to count the number of lines is by using the “wc” command with the “-l” flag which is used to display the count of lines:
$ wc -l myfile.txt
- You can also use the wc command with the cat command to display the count of lines of a file:
$ cat myfile.txt | wc -l
Using the awk command
- Another method to count the lines of the file in Linux is by using the command of awk:
$ awk 'END{print NR}' myfile.txt
Using the sed command
- The “sed” command can also be used in Linux to display the line count of the file, the use of the sed command for the purpose of displaying a number of lines is mentioned below:
$ sed -n '$=' myfile.txt
Using the Grep command
- The “grep” command is used to search, but it can be used for counting the number of lines as well as to display them, for this purpose, run the following command and replace the “myfile.txt” with your file name in the command:
$ grep -c ".*" myfile.txt
- In the above command, we have used the “-c” flag which counts the number of lines and “.*” is used as a regular pattern or we can say to find out the strings in the file, another way to use the grep command such that it also displays file name in output is the use of the “-H” flag:
$ grep -Hc ".*" myfile.txt
Using the nl command
- The number line command (nl) is used to display the numbered bullets with the lines of the file:
$ nl myfile.txt
- If you want to display just the number of lines, then use the awk command with the nl command:
$ nl myfile.txt | tail -1 | awk '{print $1}'
You must be thinking, now that you know five ways to count the number of lines, which is the best way for you? We think the wc tool is the easiest and fastest way to do something in Linux, no matter how experienced you are. If you want to know more information about this Visit Official Linux site.