Home » Linux » Shell » Bash Wc

Use wc to Count the Characters/Words/Lines [Linux/Bash]

The wc program can be used in Bash scripts and from the Linux command line to count the number of bytes, characters, words, or lines in a file. Here’s how to use it, with examples.

wc Program Syntax

The syntax for the wc command is as follows:

wc OPTIONS FILE

Note that:

  • OPTIONS should be provided from the below table of available options
  • FILE is the path to the file which will have the contents counted
    • More than one file can be specified
      • If more than one file is specified, the total counts for each file will also be displayed
  • By default, the wc command will output the lines, words, characters, and the name of the file
    • They will always be output in the same order

wc Options

The following options are available for the wc command – see below for examples of how they are used.

-c, –bytes Print byte count
-m, –chars Print character count
-l, –lines Print newline count
-L, –max-line-length Print length of the longest line
-w, –words Print word count

Additional options are available in the wc documentation.

Bytes, Characters, Words, and Lines

The byte count returned by wc will be the total number of bytes in the file. The number of characters will be the number of characters in the file – numbers, letters, and other symbols.

Words will be counted as the number of congruent runs of characters separated by spaces, while the newline count will display the number of new lines in the file. if more than one file is supplied, the total for each file will be displayed individually.

wc Command Examples

The below examples will use the following text file, called text.txt:

Unknown to man, enormous creatures
roam space and time
occasionally bumping into things

The below uses the wc commands to get the counts for text.txt:

wc test.txt

This will output:

   2      13      87 test.txt

This is the number of newlines, words, characters, and the name of the file.

Note that even though there are 3 lines, there are only two newlines in this file – creating new lines at the end of the first and second lines. There is no newline at the end of the third line!

To show the number of bytes in the file:

wc -c test.txt

Which will output:

    87 test.txt

Above, the file is 87 bytes in size. The output of wc will always be terminated with the name of the file

Below, the number of characters, words, and lines are output individually, using options:

wc -m test.txt
wc -w test.txt
wc -l test.txt

Which will output:

87 test.txt
13 test.txt
2 test.txt
SHARE:
Photo of author
Author
I'm Brad, and I'm nearing 20 years of experience with Linux. I've worked in just about every IT role there is before taking the leap into software development. Currently, I'm building desktop and web-based solutions with NodeJS and PHP hosted on Linux infrastructure. Visit my blog or find me on Twitter to see what I'm up to.

Leave a Comment