Pipes and text

Linux commands: wc

Learn how the Linux wc command counts the lines, words, and bytes in a file or piped input, plus using -l, -w, -c, and -m for characters in Unicode text.

The wc command counts things. Give it a file, or pipe some text into it, and it tells you how many lines, words and bytes it contains.

The name stands for word count, but you’ll use it for lines far more often.

Let’s create a small file and count it:

echo test >> test.txt
wc test.txt
1       1       5 test.txt

The first column is the number of lines. The second is the number of words. The third is the number of bytes. Then comes the file name.

Why 5 bytes for a 4-letter word? Because echo adds a newline at the end, and that newline is a byte too.

wc also works with pipes. Here we count the output of ls -al:

ls -al | wc
6      47     284

No file name this time, because the input came from the pipe.

Most of the time you only want one of those numbers. Use -l to count just the lines:

wc -l test.txt

-w counts just the words:

wc -w test.txt

and -c counts just the bytes:

wc -c test.txt

The combination I type most is ls | wc -l, to count how many files are in a folder. find . -name "*.md" | wc -l counts the Markdown files in a project. history | wc -l tells me how many commands my shell remembers.

Bytes are not characters

In ASCII text one byte equals one character, so -c gives you the number of characters. With non-ASCII text that’s no longer true. In UTF-8, accented letters and emoji take more than one byte.

Try it with an Italian word:

echo "città" > city.txt
wc -c city.txt
7 city.txt
wc -m city.txt
6 city.txt

-c says 7 bytes, because à takes 2 bytes plus the newline. -m says 6 characters, which is what you’d count by hand (5 letters plus the newline). When you care about characters, use -m.

A common surprise

wc -l does not count lines. It counts newline characters. That’s almost the same thing, except for the last line.

Create a file without a trailing newline and count it:

printf 'one\ntwo' > notes.txt
wc -l notes.txt
1 notes.txt

There are two lines of text, but wc reports 1, because only one newline exists. Editors usually add the final newline for you, so this bites you mostly with files generated by scripts. If a count looks off by one, this is why.

The wc command works on Linux, macOS, WSL, and anywhere you have a UNIX environment

Lesson completed