Counting Lines and Other Things

The wc command displays the number of the following in a file or pipeline:

  • Lines (-l)

  • Words (-w)

  • Characters (-c)

The following is an example of the wc command:

$ wc report7
    332   1867  11946 report7
$

Add the options -l, -w, or -c to specify if the output should include lines, words, or characters:

$ wc -l report7
    332 report7
$ wc -cw report7
   1867  11946 report7
$

This is a very useful command for counting items that can be displayed one per line. In the following example, wc -l shows that who produced 53 lines, so 53 people must be currently logged into the system:

$ who | wc -l
     53
$

For more advanced users, wc -c can be used in shell programming to calculate the length of a string:

LEN=`echo -n "$STRING" | wc -c` ...

Get Practical UNIX now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.