Linux Word Count wc Command With Example

Browse Linux commands

The wc command (as defined in the man page) print newline, word, and byte counts for each file, and a total line if more than one file is specified. Wc is widely used in bash shell scripting. Shell scripting is itself a different topic and is out of scope. Shell scripting is used to automate various linux tasks to avoid repetition of manual steps and it also saves a lot of time.

Wc Command Options

-c, --bytes print the byte counts
-m, --chars print the character counts
-l, --lines print the newline counts
-L, --max-line-length print the length of the longest line
-w, --words print the word counts

Example 1 : Basic Command

If you write the command without options as the below example

wc test
8 6 48 test

Where 8 is the lines count, 6 the word count and 48 the bytes count

Example 2 : Print Byte Count in File

The -c option can be used with wc command to display only the number of bytes in the file.

# wc -c testfile
60 testfile

Example 3 : Print number of newline

The option -l can be used to print the number of newlines in the file.

# wc -l testfile.txt
4 testfile.txt

Example 4 : Print number words in file

The option -w can be used to print the number of words in a file.

# wc -w testfile.txt
10 testfile.txt

Example 5 : Input multiple file

The wc command can accept multiple files as input.

# wc sample.txt samplefile.txt
5 9 30 sample.txt
4 7 40 samplefile.txt
9 16 70 total

Example 6 : wc used with pipes/script

To understand the proper usage of wc utility, we can look at the sample one liner

ls -l | awk '{print $3}' | wc -l

This will give us the count of new lines, and in turn provides us the count of repeated word. Similarly, if we use “uniq” utility, then the count will reduce as the no of new lines will be reduced.

ls -l | awk '{print $3}' | uniq | wc –l

Lets have a working shell script to understand another use of wc here

words=`ls | wc –l | awk {print $1}’`;
if [ $words -eq 26 ] then
echo $words
echo Good
echo Not so good

Below one liner command will count the number of times a word appears in a file

cat file-name | grep -o 'word' | wc -l

Bobbin Zachariah 9:30 am


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

All comments are subject to moderation.