5 Ways To Count The Number Of Lines In A File In Linux

How To Count The Number Of Lines In A File In Linux

There are several ways to count the number of lines in a file in Linux based operating system. There are several commands in Linux for different tasks. Every command is assigned a specific function in Linux.

5 Ways To Count The Number Of Lines In A File In Linux

1. Count the Number Of Lines Using Awk Command

You can also count the number of lines in a file using the awk command. Run the following awk command to count the number of lines in a file in Linux based operating system.

awk 'END{print NR}' filename

In the above command, NR is an awk built-in variable that represents the total number of input records (lines) processed so far.

2. Count the Number Of Lines Using Grep Command In Linux

grep is a command-line utility in Linux used to search for patterns in file. You can get the total number of lines in a file using '-e' or '--regexp' and '-c' or '--count' options.

Run the following command to count the number of lines in the file “sample.txt” using the grep command:

grep -c '^' samplefile.txt

3. Count Number Of Lines Using wc Command

wc is a command-line utility in Linux that is used to count the number of words, lines, and bytes in a file. Run the following command to count the number of lines using wc command in Linux.

wc -l filename

You can also count the number of lines in more than one file using a single command.

wc --lines filename.txt filename1.txt filename2.txt

4. Count Number Of Lines Using Sed Command In Linux

Despite being text editor, it can also be used to count the number of lines in a file. Run the following command to count the number of lines in a file using the sed command in Linux.

sed -n '$=' filename

 

5. Count the Number Of Lines Using nl and cat Commands

Run the following command to print the file content and get the total number of lines at the last line number.

nl filename.txt

Run the following cat command with '-n' to print file content with line numbers.

$ cat -n filename.txt | tail -n1
READ More Relevant Stuff:  Display And Control Your Android Device From Ubuntu 20.04

Leave a Reply

Your email address will not be published. Required fields are marked *