wc
Count lines, words, bytes and characters in files or command output
wc (word count) counts lines, words and bytes. It's most often put at the end of a pipeline to find out how many lines the previous command produced.
Syntax
wc [options] [file…]
command | wc -l
Options
| Option | What it counts |
|---|---|
-l | lines — more precisely, newline characters \n |
-w | words — runs of non-whitespace characters between spaces, tabs and newlines |
-c | bytes |
-m | characters, locale-aware (in UTF-8 an accented letter like é is 1 character but 2 bytes) |
-L | the display width of the longest line (a tab counts up to the next position that is a multiple of 8) |
--total=auto / always / only / never | when to print the total line: with several files (default) / always / only that line / never |
--files0-from=F | take the list of files from F, names separated by a null byte (- — from stdin) |
Output format
Without options, three numbers are printed — lines, words, bytes — and the file name. With options only the selected counters are shown, but always in the same order: lines, words, characters, bytes, max length — regardless of the order in which the options are written.
With several files, a total line is added at the end. If the data came from stdin, there's no file name — handy for scripts. Numbers are padded to a width, so lines may start with spaces.
Examples
printf 'one two\nthree\n' > w.txt
# everything at once: lines, words, bytes
wc w.txt
# only the line count — with and without the file name
wc -l w.txt
wc -l < w.txt
# save the number into a variable
lines=$(wc -l < w.txt)
echo "$lines"
# how many lines a command produced
ls /etc | wc -l
# how many lines matched in grep (same as grep -c)
grep 'o' w.txt | wc -l
# string length in bytes (echo adds a newline)
echo -n 'abc' | wc -c
# total over several files; the total only
wc -l /etc/passwd /etc/group
wc -l --total=only /etc/passwd /etc/group
# the longest line
wc -L /etc/passwd
# bytes and characters in UTF-8
printf 'grüße' | wc -c
printf 'grüße' | LC_ALL=C.utf8 wc -m
# lines in all .conf files from find — safe for any names
find /etc -maxdepth 1 -type f -name '*.conf' -print0 | wc -l --files0-from=- | tail -n 1
Pitfalls
wc -lcounts newlines. If the last line has no\nat the end, it isn't counted:printf 'a\nb' | wc -lprints1.wc -l fileprints the name too. For numbers in scripts, read from stdin:wc -l < file— then only the number is printed.echoadds a newline, soecho abc | wc -cgives4. For an exact length —echo -norprintf '%s'.-cis bytes,-mis characters. The sandbox locale isPOSIX, and there-malso counts bytes:grüßegives 7 with both-cand-m. WithLC_ALL=C.utf8 wc -myou get 5.ls | wc -lisn't an exact file count: a name with a newline is counted twice, andlsdoesn't show hidden files. For an exact count use find with-printf '.'andwc -c.- Empty input gives
0, not an error; a missing file is an error with code 1.
See also
grep · head and tail · uniq · find