Bash Script to Count Lines in a File
wc -l filename in a Bash script to count the number of lines in a file, or assign it to a variable with lines=$(wc -l < filename).Examples
How to Think About It
wc -l command does this efficiently by counting newline characters. The script just needs to run this command on the file and show the result.Algorithm
Code
#!/bin/bash filename="$1" if [[ ! -f "$filename" ]]; then echo "File not found: $filename" exit 1 fi lines=$(wc -l < "$filename") echo "Number of lines in $filename: $lines"
Dry Run
Let's trace counting lines in a file named 'file.txt' with 2 lines.
Check if file exists
file.txt exists, so continue
Count lines
Run wc -l < file.txt, output is '2'
Print result
Print 'Number of lines in file.txt: 2'
| Step | Action | Value |
|---|---|---|
| 1 | Check file existence | file.txt found |
| 2 | Count lines with wc -l | 2 |
| 3 | Print output | Number of lines in file.txt: 2 |
Why This Works
Step 1: File existence check
The script first checks if the file exists using [[ -f filename ]] to avoid errors.
Step 2: Counting lines
The command wc -l < filename counts the number of newline characters, which equals the number of lines.
Step 3: Output formatting
The script stores the count in a variable and prints a friendly message with the filename and line count.
Alternative Approaches
#!/bin/bash filename="$1" if [[ ! -f "$filename" ]]; then echo "File not found: $filename" exit 1 fi lines=$(awk 'END {print NR}' "$filename") echo "Number of lines in $filename: $lines"
#!/bin/bash filename="$1" if [[ ! -f "$filename" ]]; then echo "File not found: $filename" exit 1 fi lines=$(sed -n '$=' "$filename") echo "Number of lines in $filename: $lines"
Complexity: O(n) time, O(1) space
Time Complexity
The command reads through the entire file once to count newline characters, so time grows linearly with file size.
Space Complexity
The command uses constant extra space since it counts lines on the fly without storing the whole file.
Which Approach is Fastest?
All methods (wc, awk, sed) read the file once, so they have similar performance; wc -l is simplest and fastest for just counting lines.
| Approach | Time | Space | Best For |
|---|---|---|---|
| wc -l | O(n) | O(1) | Simple line count |
| awk 'END {print NR}' | O(n) | O(1) | Line count with text processing |
| sed -n '$=' | O(n) | O(1) | Line count using stream editor |
wc -l < filename to get just the line count number without the filename.wc -l filename without input redirection includes the filename in output, which may confuse scripts expecting only a number.