The wc (word count) command is used Linux and Unix systems to count the number of lines, words, characters from one or multiple text files.
Wc is a terminal command and most used in bash shell scripting for line and word counting.
In the tutorial, we learn how to use Linux wc command with some practical examples.
Wc Command and its Syntax
Below you can find the syntax for
wc [OPTION]... [FILE]...
Wc command options to print counts as follows:
--words - Print the number of words.
--bytes - print the byte counts.
--chars - Print the number of characters.
--lines - Print the number of lines.
--max-line-length - Print the length of the longest line.
By default, if wc command is used without any options it will print four columns.
For examples, lets read '/proc/meminfo' using
$ wc /proc/meminfo 47 137 1307 /proc/meminfo
47 - is the lines count
137 - the word count
1307 - the bytes count
Let check another example, how to find the number of lines in the file using
$ wc -l /proc/meminfo 47 /proc/meminfo
Count the number of lines
To count the number of lines in a text file we can use
-l option. This Line count is the most commonly used option in wc command.
The following examples show how many lines are there in the '/home/linoxide/serverlist.txt' file:
$ wc -l /home/linoxide/serverlist.txt 320 /home/linoxide/serverlist.txt
Count the number of words
If you like to count the number of words in a file you can use
-w followed by the file name.
In the following examples, you can see that the file contains '700' words.
$ wc -w /home/linoxide/serverlist.txt
Count the number of bytes in file
-c option can be used with wc command to display only the number of bytes in the file.
$ wc -c testfile 60 testfile
Count from multiple files
We can use wc command to take counts from multiple files.
In the following examples
wc command read from multiple files:
$ wc sample.txt samplefile.txt 5 9 30 sample.txt 4 7 40 samplefile.txt 9 16 70 total
Use wc command with pipes
The wc command very commonly used with a combination of different commands with pipes. Let's check some examples.
Below one-liner command will count the number of times a word appears in a file:
$ cat file-name | grep -o 'word' | wc -l
To count the number of file and directories in the current directory
$ ls -1 | wc -l 2
To count the number of files in the current directory.
$ find . -type f | wc -l
$ find -type f -printf '.' | wc -c
In this tutorial we learned how to use wc command to count number lines, files and words. I hope you enjoyed reading and please leave your suggestions in the comment section.