wc — count lines, words and bytes
The wc command counts lines (-l), words (-w), bytes (-c) and characters (-m) in a file or in command output.
Cheat sheet
7 commands Printable version-
wc file.txtlines, words, bytes and the name -
wc -l file.txtlines only: "2 file.txt" -
wc -l < file.txtjust the number: "2" -
grep error app.log | wc -lhow many lines contain error -
wc -l *.logper file, plus a total -
find /etc -name '*.conf' | wc -lhow many files were found -
wc -m text.txtcharacters, not bytes
Overview
wc (word count) prints three numbers: lines, words and bytes. A word is a run of
text between spaces, tabs and newlines. -l, -w and -c keep only the number you
need:
wc counts a line for every newline character. When the file name is an argument,
wc prints it next to the number. When the text arrives on standard input — through
< or a pipeline — there is no name, just the number, which is handy in scripts
and comparisons.
Options
5Options combine: wc -lw prints lines and words. The full list is in man wc.
| Option | What it does | Example |
|---|---|---|
-l --lines |
Count lines (newline characters). | wc -l app.log |
-w --words |
Count words separated by whitespace. | wc -w notes.txt |
-c --bytes |
Count bytes. | wc -c image.png |
-m --chars |
Count characters by locale; in UTF-8 a Cyrillic letter is one character. | wc -m text.txt |
-L --max-line-length |
Width of the longest line. | wc -L config.yaml |
Nothing found. Try a shorter query.
Recipes
5How many files are in a directory
ls | wc -l counts too, but skips hidden files, and ls -l | wc -l adds the total
line.
How many distinct values
Several files at once
The longest line
Troubleshooting
5wc -l shows one line fewer
wc counts newlines. If the last line of a file has no \n, it is not counted:
printf 'a\nb' | wc -l prints 1.
There is an extra file name in the output
The name is printed when the file is an argument. Feed the file on standard input
instead: wc -l < file.txt.
wc -c and wc -m give different numbers
-c counts bytes, -m counts characters according to the locale. In UTF-8 a
Cyrillic letter is one character and two bytes: for привет plus a newline, -c
gives 13 and -m gives 7.
ls | wc -l gives the wrong number of files
ls without -A skips hidden files, and ls -l adds a total line. Count with
find … | wc -l.
wc: x: Is a directory
wc reads files, not directories. To count the files in a directory use find:
find x -type f | wc -l.
See also
- grep — pick lines before counting;
grep -ccounts on its own. - sort and uniq — remove repeats to count distinct values.
- find — find the files you then count.
- redirection — input from a file with
<and the|pipeline. - text-tools — tr, paste, column and other pipeline links.
Found an inaccuracy? Report an error in the article