When to use "cat -n" instead of "wc -l"

April 6, 2025

Problem

wc -l is pretty good at counting lines, it’s what most people use

# man cat | wc -l
71

Except that it collapses all your data to a single number.

There’s nothing wrong with that if you’re only trying to get the answer.

But when you’re building long one-liners with multiple pipes, it’s useful to answer two questions at the same time

Quizzes

For example:

show answers
# seq 3 14 | cat -n
     1  3
     2  4
     3  5
     4  6
     5  7
     6  8
     7  9
     8  10
     9  11
    10  12
    11  13
    12  14


How about:

show answers
# look . | grep '^.b..t$' | cat -n
     1  abaft
     2  abbot
     3  abdat
     4  abnet
     5  abort
     6  about
     7  abret
     8  absit

cat -n

The cat command doesn’t have too many flags, but more than I expected. The exact details will depend on the GNU or BSD variant.

-n, --number
    number all output lines

So, while it seems that you might only use cat -n to print a file with line numbers, keep in mind that the last line number is wc -l

man cat | cat -n

Discuss on Bluesky