Counting with wc

wc counts lines, words and characters in text.

Syntaxwc [-l|-w|-c] [file]

wc ("word count") reports how much text there is. With no options it prints three numbers: lines, words and bytes.

Options

  • -l — count lines only.
  • -w — count words only.
  • -c — count bytes; -m counts characters.

By far the most common use is wc -l at the end of a pipe to answer "how many?" — how many matches, how many files, how many users.

Example

Example · bash
# Lines, words and bytes
wc notes.txt
#  12  84  532 notes.txt

# Just the number of lines
wc -l notes.txt
# 12

# How many .txt files are here?
ls *.txt | wc -l

# How many users can log in?
grep -c bash /etc/passwd

When to use it

  • A developer runs 'wc -l *.py' to get a line count per file and total across a Python project.
  • A CI job uses 'cat test_results.txt | wc -l' to fail the build if fewer than a minimum number of tests ran.
  • A sysadmin checks 'wc -c /var/log/syslog' to see the log file's byte size before deciding to rotate it.

More examples

Count lines, words, and bytes

Shows the default wc output (lines, words, bytes) and the -l flag to get only the line count.

Example · bash
wc /etc/passwd
#   45   90 2513 /etc/passwd
# lines words bytes filename

# Count lines only
wc -l /etc/passwd
# 45 /etc/passwd

Count lines across multiple files

Counts lines in each file individually and provides a grand total at the bottom.

Example · bash
wc -l src/*.py
#   102 src/app.py
#    58 src/utils.py
#    34 src/models.py
#   194 total

Use wc in a pipeline

Uses wc -l at the end of pipelines to count matching lines, a common pattern for metrics and checks.

Example · bash
# Count how many running processes match 'python'
ps aux | grep python | grep -v grep | wc -l

# Count unique IPs in access log
awk '{print $1}' access.log | sort -u | wc -l

Discussion

  • Be the first to comment on this lesson.