Linux WC Command to Count Characters, Words, and Lines in a File

The Linux wc utility in Linux counts the number of bytes, characters, words, and lines in a file or in standard input. This is a small but very useful utility provided among various utilities in Linux. This article explores wc command

By default, wc takes its input from STDIN. The default output counts number of bytes, number of words and number of lines.

$ wc
2 2 12

To provide input from STDIN, we just invoke wc command with no option or argument. When we are done inputting, we enter ctrl+d to provide end of file mark. This output says that the input has 2 lines, two words and 12 bytes. Now if your counting of characters is different from the output, then remember to include hidden characters like newline character. Let's see another example:

$ wc
Hello all
This is demonstration of wc command.
2 8 47

1) Character and byte count

To print no of bytes of a file, -c or --bytes option is used.

$ cat wcfile.txt
Hello world. First Line.
Another line

$ wc -c wcfile.txt
45 wcfile.txt

$ wc --bytes wcfile.txt
45 wcfile.txt

For number of characters, -m or --chars options are used.

$ wc -m wcfile.txt
45 wcfile.txt

$ wc --chars wcfile.txt
45 wcfile.txt

2) Word count

If we wish to print just the number of words in a the input, we use -w option.

$ wc -w wcfile.txt
7 wcfile.txt

$ wc --words wcfile.txt
7 wcfile.txt

The --words option does the same.

3) Line count

The number of lines in a file are printed by -l option. This can also be achieved with --lines option.

$ wc -l wcfile.txt
3 wcfile.txt

$ wc --lines wcfile.txt
3 wcfile.txt

The length of longest line is printed by -L or --max-line-length option.

$ wc -L wcfile.txt
24 wcfile.txt

$ wc --max-line-length wcfile.txt
24 wcfile.txt

In this case, the first line is the longest line having 24 characters.

4) File count in directory

Below commands will find the total file count in a directory in Linux. Find might be bit faster if you want to count huge number of files. ls -f (this will not sort) will be more faster than normal ls.

$ ls -l | wc -l


$ find ./ -type f | wc -l

Please leave your suggestions on this article in the below comment section.

Bobbin Zachariah 8:09 am


Your email address will not be published. Required fields are marked *

All comments are subject to moderation.