Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Count lines in a file using Linux bash
Counting lines in a file is a fundamental task in Linux system administration and text processing. Whether you're analyzing log files, processing data, or managing configuration files, knowing how to quickly determine the number of lines helps with file size estimation and data analysis. Linux provides several built-in commands to accomplish this task efficiently.
Sample File Setup
For demonstration, we'll use a text file called programming.txt containing popular programming languages:
$ cat programming.txt JavaScript Java C Python C# PHP C++ Go R Ruby
This file contains 10 lines. Let's explore different methods to count them automatically.
Method 1: Using wc Command
The wc (word count) command is the most common and efficient way to count lines. The -l flag specifically counts lines:
$ wc -l programming.txt 10 programming.txt
The output shows the line count (10) followed by the filename. To get only the number without the filename, use input redirection:
$ wc -l < programming.txt 10
You can also pipe the file content through wc:
$ cat programming.txt | wc -l 10
Method 2: Using sed Command
The sed (stream editor) command offers two approaches for line counting. First, printing all line numbers:
$ sed -n '=' programming.txt 1 2 3 4 5 6 7 8 9 10
This approach becomes impractical for large files. A better method uses $= to print only the last line number:
$ sed -n '$=' programming.txt 10
Method 3: Using awk Command
The awk command treats each line as a record and uses the built-in NR (Number of Records) variable:
$ awk 'END { print NR }' programming.txt
10
This method is particularly useful when you need to perform additional text processing along with counting.
Method 4: Using cat Command
The cat command with the -n option shows line numbers, but displays the entire file content:
$ cat -n programming.txt
1 JavaScript
2 Java
3 C
4 Python
5 C#
6 PHP
7 C++
8 Go
9 R
10 Ruby
While this shows the line count, it's inefficient for large files since it displays all content.
Performance Comparison
| Method | Command | Efficiency | Use Case |
|---|---|---|---|
| wc | wc -l file.txt |
Highest | General line counting |
| sed | sed -n '$=' file.txt |
Good | Text processing workflows |
| awk | awk 'END {print NR}' file.txt |
Good | Complex text analysis |
| cat | cat -n file.txt |
Lowest | Small files with content review |
Conclusion
The wc -l command is the most efficient and commonly used method for counting lines in files. For simple line counting tasks, especially with large files, it provides the fastest results with minimal resource usage.
