The wc (word count) command in Linux allows you to count words, lines, and characters in a text file or the output of a command. It commonly becomes useful to analyze text data.
Syntax
The basic syntax of wc command
wc [options] [file]
Below are the 5 most useful options of wc:
-l
or--lines
: Count the number of lines.-w
or--words
: Count the number of words.-c
or--bytes
: Count the number of bytes (characters).-m
or--chars
: Count the number of characters.-L
or--max-line-length
: Find the length of the longest line.
By default wc command displays the number of lines, words, and characters in the specified file.
$ cat linux-info.txt
Linux is open source and used widely.
It's known for multitasking and stability.
Distros like Ubuntu and Debian exist.
Linux CLI is powerful.
Community supports its growth.
$ wc linux-info.txt
9 27 177 linux-info.text
$
Examples
Let's look at how to use wc command with some examples
Count Lines
Use -l option to count the number of lines and display the total.
$ wc -l linux-info.txt
9 linux-info.text
You can count lines in multiple files by providnig more filenames:
$ wc -l linux-info.txt .bash_history
9 linux-info.text
1260 .bash_history
1269 total
This displays the total line count in each file and the overall lines in the files.
Count Words
Use -w option to count the number of words, the following examples check the total word count in the linux-info.txt file:
$ wc -w linux-info.txt
27 linux-info.text
Whereas counting the words in the provided string, use
$ echo "It's known for multitasking and stability." | wc -w
6
Count Characters
Use -c option to count characters in a file or input stream.
$ echo "It's known for multitasking and stability." | wc -c
43
The 43 output shows the counts the characters (bytes) in the provided string.
Note: It treats each byte, including control characters, newline characters ('\n'), and special characters, as a single character.
The -m option does the same but treats multibyte characters as a single-character, and does not consider control characters or special characters as individual characters.
Length of the longest line
The wc -L
command helps to check the length of the longest line in a text file.
$ wc -L linux-info.txt
42 linux-info.txt
The output 42 means there is a line in the file that is 42 characters long. Remember this may not necessarily be the same as the total number of bytes.
Few Practical Examples:
1. Count the number of times a specific word appears in a file:
$ grep -o -w 'linux' linux-info.txt | wc -l
0
$ grep -o -w 'Linux' linux-info.txt | wc -l
2
2. Count the total number of files and directories in the current directory
ls -1 | wc -l
orfind . -type f | wc -l
3. Count the total number of users on the Linux system
getent passwd | wc -l
Basically, it counts the number of user entries in the system's password database.
Comments