Counting with wc
How Big Is This File?
Sometimes you need a quick answer to a simple question: how many lines are in this file? How many words? The wc (word count) command gives you these numbers instantly.
Basic Usage
Run wc on any file and it gives you three numbers:
wc ~/projects/my-app/src/index.js
The output looks something like:
42 156 1203 /home/user/projects/my-app/src/index.js
Those three numbers are:
| Number | Meaning |
|---|---|
| 42 | Lines |
| 156 | Words |
| 1203 | Characters (bytes) |
Most of the time, you don’t need all three. That’s where the flags come in.
The Flags
-l (Lines)
Count only the number of lines:
wc -l ~/projects/my-app/src/index.js
Try it now. This is by far the most common use of wc. “How many lines of code is this file?” is a question that comes up constantly.
-w (Words)
Count the number of words:
wc -w ~/Documents/notes.txt
Try it now. Useful for text documents, less so for code.
-c (Characters)
Count the number of characters (bytes):
wc -c ~/projects/my-app/src/index.js
This tells you the file size in bytes. Handy for quick size checks.
A Preview of Piping
Here’s something interesting. You can send the output of one command into wc using the | (pipe) character:
cat ~/projects/my-app/src/index.js | wc -l
This takes the output of cat (the file contents) and feeds it into wc -l (count lines). The result is the same as wc -l filename, but this pattern — called piping — becomes incredibly powerful when combined with other commands.
Piping is a huge topic that gets its own module later in the course. For now, just know that the
| character connects commands together, sending the output of one into the input of another. AI tools chain commands like this all the time.
Try it now: Type cat ~/projects/my-app/src/index.js | wc -l and compare the result to wc -l ~/projects/my-app/src/index.js. Same answer, different approach.
Practice
Try these in the terminal:
wc -l ~/projects/my-app/src/index.js— how many lines in index.js?wc -w ~/Documents/notes.txt— how many words in your notes?wc ~/projects/my-app/README.md— get all three counts at oncecat ~/projects/my-app/src/index.js | wc -l— try piping for the first time