Counting with wc
The wc command counts lines, words, and characters in files. It's simple but incredibly useful for file analysis.
Basic Usage
wc filename
Output shows: lines, words, characters, filename
Understanding the Output
10 45 256 file.txt
│ │ │ │
│ │ │ └── filename
│ │ └── characters (bytes)
│ └── words
└── lines
wc Options
| Option | Shows |
|---|---|
-l | Lines only |
-w | Words only |
-c | Characters (bytes) only |
-m | Characters (multi-byte safe) |
-L | Longest line length |
Exercise: Count Lines
Count the number of lines in a file:
Counting Multiple Files
wc *.txt # Each file and total
wc -l *.log # Lines in each log
Common Use Cases
Count Lines of Code
wc -l *.py # Python files
wc -l src/*.js # JavaScript files
find . -name "*.js" | xargs wc -l # Recursive
Count Log Entries
wc -l /var/log/syslog
Check File Size (characters)
wc -c large_file.txt
Combining with Pipes
Count Output Lines
ls | wc -l # Number of files
ps aux | wc -l # Number of processes
grep "error" log.txt | wc -l # Number of errors
Count Unique Items
cat file.txt | sort | uniq | wc -l
Practical Examples
How Many Users?
wc -l /etc/passwd
Lines in All Files
wc -l *.txt
Longest Line
wc -L config.txt # Useful for column width
Comparison: Different Counts
| What you want | Command |
|---|---|
| Total lines | wc -l file |
| Non-empty lines | grep -c . file |
| Lines matching pattern | grep -c pattern file |
Key Takeaways
wccounts lines, words, and characters- Use
-lfor just lines (most common) - Use
-wfor just words - Combine with pipes to count command output
- Essential for analyzing text files and logs

