What does the wc command count, and how do you use its options?
wc counts lines, words and bytes in a file or input. wc -l counts lines, -w words, -c bytes and -m characters. It is most often used at the end of a pipeline, such as grep error log | wc -l, to count matches.
Explain it simply
wc stands for word count. Think of the counter at the bottom of a Word document, but with a separate number for each unit.
Run wc file and it prints three numbers plus the name: lines, words and bytes. The options pick one: -l lines, -w words, -c bytes, -m characters (differs from bytes for non-English text such as Hindi in UTF-8) and -L the length of the longest line.
Common uses: ls | wc -l counts files in a folder, grep -c or grep ERROR log | wc -l counts matching lines, and wc -l < file prints just the number without the file name.
A detail that confuses people: wc -l counts newline characters. If the last line has no trailing newline, it is not counted, so a file with "a\nb" reports 1, not 2.
Example
printf 'one two\nthree\n' > t.txt
wc t.txt
# 2 3 14 t.txt
wc -l < t.txt
# 2
ls /etc | wc -lWhat to say in the interview
"wc counts lines, words and bytes; -l, -w, -c and -m select one. I mostly use wc -l at the end of a pipeline to count results. I remember it counts newline characters, and -m versus -c differ for multi-byte text."
Common mistakes
- Expecting wc -l to count a last line without a newline.