← Linux and the Command Line
Lesson 24 of 51 · 10 XP
wc — counting lines, words and bytes
Theory and problem statement
Machine translation, not yet reviewed by a native speaker.
wc (word count) counts:
wc file.txt # lines, words, bytes and the file name
wc -l file.txt # only lines
wc -w file.txt # only words
wc -c file.txt # bytes
wc -m file.txt # characters (in UTF-8 an accented or a Cyrillic letter is 2 bytes, but 1 character)
If the data comes through a pipe or <, the file name isn't printed — only the number. That's more convenient in scripts:
count=$(grep -c ERROR app.log)
lines=$(wc -l < app.log)
How many files are in a folder? ls | wc -l. How many lines of code are in a project? find . -name "*.c" | xargs cat | wc -l.
wc -l counts line break characters. If the last line of a file doesn't end with \n, it isn't counted. That's a classic trap.
Task. The input is a text. Print three numbers, each on its own line: the number of lines, the number of words and the number of non-empty lines.
Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.