wc Command Guide
The wc (word count) command counts lines, words, and characters in files. Learn how to gather statistics about your text data.
4 min read•Last updated: 2024
Dai Aoki
CEO at init, Inc. / CTO at US & JP startups / Creator of WebTerm
Quick Reference
Basic
wc fileLines, words, byteswc -l fileCount lineswc -w fileCount wordsOptions
-cCount bytes-mCount characters-LLongest line lengthCommon
cat file | wc -lLines from pipels | wc -lCount fileswc -l *.txtLines in each fileDownloadable Image Preview
Failed to generate preview
Basic Usage
By default, wc displays lines, words, and bytes.
bash
wc file.txt
# Output: 10 50 300 file.txt
# lines words bytesCommon Options
wc Options
| -l | Count lines only |
| -w | Count words only |
| -c | Count bytes only |
| -m | Count characters only |
| -L | Show length of longest line |
Counting Specific Items
bash
# Count lines only
wc -l file.txt
# Count words only
wc -w file.txt
# Count bytes only
wc -c file.txt
# Count characters (handles multi-byte)
wc -m file.txt
# Longest line length
wc -L file.txtInfo
-c counts bytes while -m counts characters. These differ for multi-byte characters (like UTF-8).Multiple Files
bash
wc file1.txt file2.txt file3.txt
# 10 50 300 file1.txt
# 20 100 600 file2.txt
# 15 75 450 file3.txt
# 45 225 1350 totalUsing with Pipes
bash
# Count lines from command output
ls | wc -l
# Count matching lines from grep
grep "error" log.txt | wc -l
# Count files in directory
find . -type f | wc -l
# Count running processes
ps aux | wc -lPractical Examples
Count lines of code
bash
# Single file
wc -l script.py
# All Python files
find . -name "*.py" -exec wc -l {} + | tail -1
# Excluding blank lines
grep -v '^$' file.py | wc -lCount files by type
bash
# Count JavaScript files
find . -name "*.js" | wc -l
# Count directories
find . -type d | wc -lCount unique items
bash
# Unique words in file
cat file.txt | tr ' ' '\n' | sort -u | wc -l
# Unique IP addresses in log
awk '{print $1}' access.log | sort -u | wc -lMonitor log growth
bash
# Lines added to log
before=$(wc -l < log.txt)
# ... time passes ...
after=$(wc -l < log.txt)
echo "New lines: $((after - before))"Count errors in logs
bash
grep -c "ERROR" application.log
# Or using wc
grep "ERROR" application.log | wc -lCheck if file is empty
bash
if [ $(wc -l < file.txt) -eq 0 ]; then
echo "File is empty"
fiOutput without Filename
Use input redirection to get count without filename:
bash
# With filename
wc -l file.txt
# Output: 10 file.txt
# Without filename
wc -l < file.txt
# Output: 10Related: Code Statistics
For detailed code statistics, consider specialized tools:
bash
# cloc - Count Lines of Code
cloc .
# sloccount - Source Lines of Code
sloccount .
# tokei - Fast code statistics
tokeiSummary
wc is essential for quick file statistics. Key takeaways:
- Use
wc -lfor line count - Use
wc -wfor word count - Use
wc -cfor byte count - Use
wc -l < filefor count without filename - Combine with pipes for counting command output