Look inside a file

INPUT · Slides

Counting things

01 / 08

Counting without looking

So far every tool has been about looking at what is inside.

But sometimes the only thing you want is a number. How many lines is this log? How many files are there? You do not need the contents for that.

The tool for counting is wc.

02 / 08

wc — lines, words and bytes

wc is short for word count, but it actually gives you three numbers at once.

Left to right: lines, words, bytes. Despite the name, words are only one of them.

~ $ wc english.txt      2       4      25 english.txt

03 / 08

-l for lines only

You rarely want all three, so people normally narrow it down with an option.

  • -l — lines
  • -w — words
  • -c — bytes (the c is from characters, but what it counts is bytes)

-l is the one you use most, because "how many of them are there" comes up all the time.

~ $ wc -l names.txt5 names.txt

04 / 08

A byte is not a character

What -c counts is bytes, not characters. Usually they look the same, but put in a letter with an accent and they part company.

café is four letters. But é is not in the plain alphabet, and it takes two bytes, so café is five bytes. Add the newline and that is six.

When you want the number of characters, use -m.

~ $ wc -c cafe.txt6 cafe.txt~ $ wc -m cafe.txt5 cafe.txt

05 / 08

Pour it in and the file name disappears

wc can count things poured into it with |, without being given a file name at all.

When you do that, the file name on the right stops appearing, because what it counted had no name.

That is a small thing but a useful one. When all you want is the number, pouring it in gives you something you can use as it is.

~ $ cat names.txt | wc -l5

06 / 08

Counting how many files there are

This might be the commonest use of wc -l there is.

ls | wc -l tells you how many things are in there. ls puts out one name per line, and wc -l counts them.

All it saves you is counting with your eyes, but with a hundred of them that is quite a saving.

~ $ ls | wc -l4

07 / 08

Hand it two or more and you get a total

Hand it two or more files and a total line gets added after the individual numbers.

That is the shape for "how many lines are there in this whole directory".

~ $ wc -l names.txt english.txt      5 names.txt      2 english.txt      7 total

08 / 08

Now have a go

Marking looks at whether the number is right, so do not miscount.

Though counting is wc's job. Yours is only to decide what it should count.