In this article, we would cover how to count words, bytes and lines in a file using wc command-line utility. The following is the syntax for wc command –
wc [options] [file_name]
We explain the command-line utility – wc through relevant examples next.
Count lines, words and characters in a file
Let’s say we have a text file test
. And, it has 16 words and 77 characters spread across 3 lines.
Hello World! It is a test file to check for number of lines, words and bytes
So, if we use the basic wc command without any options then,
wc test
It would return with the following output –
3 16 77 test
From the above we can see that, though it doesn’t specifically elaborate the data, the first output is for number of lines, then comes the words and lastly the number of characters in the file test. And, the following order is specified in its man pages for the output –
newline, word, character, byte, maximum line length
But, what if we just want to know the number of words or something else in a file. In that case, we need to use options along-with wc command. So, for number of words –
wc -w test
It returns with –
16 test
To count the number of lines –
wc -l test
Outcome –
3 test
And, to count the number of characters in the file –
wc -m test
Here, the output would be –
77 test
Bytes and maximum display width in a file
Up till now, we have covered number of lines, words and characters. Next is byte size, we use -c option
wc -c test
It would return with –
77 test
And, lastly to print the maximum display width –
wc -L test
Output –
32 test
wc on multiples files
With the basics done, we can also check the data for multiple files as well. Let’s say, if we have the copy of file test as test1 –
cp test test1
Now, to check for both the files –
wc test test1
The outcome is self-explanatory –
3 16 77 test 3 16 77 test1 6 32 154 total
Apart from that, we can also use special characters like (*) – asterisk
wc test*
We can also use options with multiples files as well –
wc -w test test1
Output –
16 test 16 test1 32 total
In conclusion, we have covered various wc command-line options here through relevant examples.