Count the Number of Words in a File Using the 'wc' Command

Count words, lines, and bytes within text files using a two-character command

Collection of various wood type letters for printing

klikk / Getty Images

The Linux wc command provides the total number of words in a file.

This command only works on plain-text files. More complex files, like documents saved in Rich Text Format, contain additional command codes that, although you don't see them when you open the file in an RTF-capable word processor, are nevertheless embedded in the document.

How to Use the "wc" Command

The basic usage of the "wc" command is as follows:

For example, a text file titled declaration.txt contains a key line from the Declaration of Independence. Executing the command

reveals data about the text within that file:

the wc command in linux

The command reveals three numbers — 2 35 211 — plus the filename.

Those values indicate three contextual data points:

  • The first number is the number of new lines of characters
  • The second number is the number of words
  • The third number is the number of bytes (i.e., the number of characters, visible or not)

Get the Total Word Count From Several Files

The wc command supports several filename arguments. For example, if we duplicate the declaration.txt as declaration2.txt, then run the wc command on both files, we'll see the totals for each and then the totals for both:

wc command

Command Switches

Adding a command switch refines the results of the wc command. It supports:

  • -c: Displays only the number of bytes and the filename
  • -m: Displays only the number of characters
  • -l: Displays only the number of lines
  • -w: Displays only the number of words

A line is a logical function; it's not affected by word wraps. In the example declaration.txt, we inserted a hard line break to show the entire quote on the screen, which is why the wc command lists two lines. If we had not inserted the manual line break, the quote would have stretched off the side of the screen, but it would have shown only one line of text.

Use 'wc' in Command Pipes

As with most shell commands, wc supports piping to arrive at more complex outputs. For example, to find the counts of all the words of all text files in a folder, use the following command:

This combines the find command with the wc command. The find command looks in the current directory (denoted by .) for all documents of type file and then prints the name with a null character, which is required by the wc command. The wc command takes as input the output from find and processes each file name returned by the find command.