WC (word count) is the Linux command which allows you to count the number of bytes(or characters), words and lines in a provided text file. It might not seem very useful, but there are actually a lot of situations where you might need to get the number of words or lines in a file without writing a single line of code.
Let’s go through some examples below:
Example 1. Default usage
The most basic usage is wc followed by the input filename:
This will output the number of lines, words and bytes in the file:
The sample file contains 3 lines, 12 words and 60 bytes.
The image above shows that we can also count only lines, words or bytes in a file, using the special options:
wc -c or wc –bytes will count only bytes
wc -w or wc –words will count only words
wc -l or wc –lines will count only lines
Example 2. Count the number of characters
There’s another options which allows us to count the number of characters in a file:
wc -m <FILENAME>
wc --chars <FILENAME>
The file contains 60 characters.
The number of characters will be different from the number of bytes if the characters in a file are using more than one byte each.
Example 3. Print the length of the longest line
To print the length of the longest line us the following command:
wc -L <FILENAME>
wc --max-line-length <FILENAME>
The second line in the file is the longest one, therefore the command returns its length – 29.
Example 4. Command Help
Use command help if you forget how to use the available options: