6 Ways to Count the Number of Lines in a Linux File

Want to count the number of lines in a Linux file? We'll provide you with a few different ways to do it. Counting the number of lines gives information about how small or large a given file is. Like all computer files, Linux files come in different sizes. Some files are big, and some are

Quick Links

Key Takeaways

  • You can use the wc command with the "-l" option to find the line count of a file (wc -l filename). This will also print the name of the file.
  • A combination of the sed command with the "-n" option can also give you a line count (sed -n '=' filename). This command will print the line numbers without the contents of the file.
  • Run the awk command with the built-in "NR" variable to get the line count of a file (awk 'END {print NR}' filename).

Want to count the number of lines in a Linux file? We'll provide you with a few different ways to do it. Counting the number of lines gives information about how small or large a given file is.

Why Count the Lines in a File?

Like all computer files, Linux files come in different sizes. Some files are big, and some are small. Linux users frequently need to check the file size to manage system disk space and avoid running out of storage. One way of doing this is to count the number of lines a file has, albeit roughly. Just as the thickness of a book generally indicates its length, the number of lines in a file can in some situation give you a relative sense of its size.

Counting the lines of a file is useful for various reasons. You can verify the format or structure of the file. It can also measure the size and complexity of a text file, such as a source code file, a configuration file, or a log file.

Line count can help you to filter and analyze the output of other commands. For example, one can analyze the number of lines in a system log file. This will help you to check the approximate number of errors present in the system log file.

Line count also gives you an estimate of the total items in a directory. By counting the lines in a file over time, you can track changes to the file, such as the addition or removal of lines. This can be useful for debugging software or tracking changes to a document.

How to Count Lines in a File on Linux

Linux provides a variety of commands and tools that make it easy to figure out how many lines are in a file. Some of these commands are wc, sed, grep, and awk. A Bash script can also help calculate the line count in a file. We will explore each of these methods with an example.

1. Count Words, Lines, and Characters in a File Using wc

Do you want a simple way to count the lines in a file? Simply use the wc command. This command outputs the number of words, lines, and characters in a file.

Let's consider a sample file, example.txt. This file contains a list of a few beginner Linux commands:

To count the lines of the specified file named example.txt, add the -l flag with the wc command followed by the file name:

wc -l example.txt

The above output displays only the line count. To get detailed information about the file, use the wc command without any option. The wc command, with no flags, will print the word count, lines, and characters of a file in a single command:

wc example.txt

Now, let's suppose you have three files named example.txt, new.txt, and new1.txt. To count the number of lines of multiple files, simply use the wc command with the -l option followed by file names.

wc -l example.txt new.txt new1.txt

The wc command can also display the line count of all the files present inside a directory. To do this, use the wc command with the -l option followed by the asterisk operator.

wc -l *

As in all the above cases, the output shows the filename along with the line count. To show the line count without the filename, run:

wc -l < example.txt

Here, the wc command uses input redirection. This will give the content of the example file to the wc command. It then directly counts lines without displaying the filename.

Another way to count lines in a file is by piping the output of the cat command with the wc -l command.

cat example.txt | wc -l

2. Count and Display Line Numbers of a File Using sed

The sed command, or stream editor, is an essential command-line tool for text manipulation on Linux. It performs various operations on a file, such as inserting, deleting, replacing, or appending text. The sed command takes the input from a file or standard input.

The sed command can also count the total lines of a specified file. It can take different arguments to print the line numbers.

Run the sed command with the -n option and an equal sign to sequentially count and show line numbers on separate lines.

sed -n '=' example.txt

Sometimes, obtaining the total line count is more efficient than retrieving individual line numbers for each line in the file. The sed command with the options -n and $= can count and display the total number of lines in the file. The $= signifies the last line of the file. It ensures that only the line number is printed to the standard output.

To get an overall number of lines in the file, use:

sed -n '$=' example.txt

3. Using grep to Count the Number of Lines in a File

The grep command is specifically used for searching for a pattern inside a file. Not only that, but it can also give us the total count of lines that correspond or do not correspond to the defined pattern. The defined pattern is a regular expression that specifies what to search for.

If you don't specify the file, grep reads from the standard input.

Add the -c flag with the grep command to determine the count of lines matching a specific pattern. For example, to count the lines in a file that contain the word "Command," run:

grep -c Command example.txt

It is also possible to filter and easily count the lines that don't contain a particular word or pattern.

For this, use the -v flag with grep:

grep -c -v awk example.txt

There is another regular expression pattern (".*") with a dot and asterisk sign. It matches any line with zero or more occurrences of any character. Unlike the above two commands, it doesn't look for a specific word. It simply counts and outputs the number of lines in example.txt that have one or more characters.

grep -c ".*" example.txt

The -c flag ensures that only the line count is displayed, not the actual line content that matches the pattern.

To add the file name in the above output, simply include the -H flag:

grep -Hc ".*" example.txt

The awk command is used for text processing and as a tool for data extraction and reporting. It's particularly strong in pattern matching and processing fields and records.

You can use the awk command to count the lines in a file. It uses the AWK programming language to print the total number of records (lines) in the file.

awk 'END {print NR}' example.txt

The given awk script END {print NR} is executed after processing all lines in the example.txt file. The script instructs awk to print the value of NR, which represents the total number of records (lines) processed.

5. Listing and Counting Lines in a File With the nl Command

The nl command adds line numbers to the specified file contents. It's useful for viewing or printing files with line numbers. You can use the nl command with filename to count the lines in a specified file.

nl example.txt

This command will display both the line numbers and line content in the example.txt file.

However, it is not an efficient way to get a line count of files, especially for large files. It involves additional processing and rendering of output that is not necessary for the specific task of counting lines. Imagine a file with thousands of lines, and you have to scroll all the way down to get the total count of lines.

If you want to know the total line count without any other information, pipe the output of the nl command with tail and awk.

nl example.txt | tail -1 | awk '{print $1}'

The nl command adds a line number at the beginning of each line. Then the output of the nl command is piped with the tail command, which displays the last line of the input. The -1 option tells the tail command to show only one line. Till now, you have the output "10 uname Command."

Next, this output is given as input to the awk command, which prints a specific field from the input. The {print $1} argument tells the awk command to print the first field, which is the line number. For example, if the input is "10 uname Command," the awk command will print the first field, which in this case is the line number 10.

6. Using Bash Script to Count the Number of Lines in a File

Bash scripting, a handy tool on Linux systems, is commonly used to automate tasks. You can also use it to count the lines in a file. You can write a custom Bash script, which uses the wc command to print the line count of a file:

#!/bin/bash
filename=$1
linecount=$(wc -l < "$filename")
echo "The file $filename has $linecount lines."

This Bash script uses the wc command with the -l flag. The wc command gets the count of lines and stores it in the linecount variable. At the end of the script, a message is echoed to the terminal, which displays the filename and its corresponding line count.

To use the above script, simply save it as a file with the ".sh" extension (count_lines.sh) and make it executable using chmod:

chmod +x count_lines.sh

Now, run the script using the ./ notation followed by the script's name:

./count_lines.sh example.txt

You will get the total line count of the file example.txt to the standard output.

Know Your Linux File System Inside and Out

On Linux, it is important to know the files on your system. Like counting lines, counting Linux files in a directory also helps you manage the system more efficiently. This will help you know what files are taking up the most space, what to delete, and what to keep.

Knowing the Linux file structure is also important. Consider the main pillar of Linux files–the inodes. If you run out of these in your system, you will have a tough day. These are very limited in numbers and store crucial data in your system.

Knowing these will not only help you to manage and perform tasks but also ease the system maintenance tasks.

ncG1vNJzZmivp6x7qbvWraagnZWge6S7zGiumrGjYsGwecKorKesXaPCrq7Eq2Sonl2htq%2Bx0magp2Wcnru2xIyfoKWdo2Q%3D

 Share!