Bash: How to Count Number of Words in String


Often you may want to use Bash to count the number of words in a particular string.

You can use the following methods to do so:

Method 1: Count Number of Words in a String

wc -w <<< "$my_string"

This particular example will return the total number of words in the string variable named my_string.

Note that we use the wc (“word count”) command along with -w to specify that we want to count the total words in the string as opposed to the number of bytes ( -c ) or the number of lines ( -l ).

Method 2: Count Number of Words in Each Line in File

awk '{ print NF }' some_strings.txt

This particular example will return the total number of words in each line in the file named some_strings.txt.

Note that if you’d like to return the line itself along with the total word count of the line, you can use the following syntax:

awk '{ print $0, NF }' some_strings.txt

The following examples show how to use each of these methods in practice.

Example 1: Count Number of Words in String

We can use the following syntax to create a string variable named my_string and then count the total number of words in it:

my_string="I hope you have a great day"
wc -w <<< "$my_string"

The following screenshot shows how to use this syntax in practice:

Bash count words in string

This returns a value of 7, which tells us that there are 7 total words in the string.

We can manually count the number of words in the string we created to verify that this is indeed correct.

Example 2: Count Number of Words in Each Line in File

Suppose that we would like to count the number of words in each line of a file named some_strings.txt.

We can use the cat command to first view the contents of the file:

We can then use the following syntax to count the number of words in each line of the file:

awk '{ print NF }' some_strings.txt

The following screenshot shows how to use this syntax in practice:

The output displays the number of total words in each line in the file.

If we would like to display the number of words in each line along with the line itself, we can use the following syntax:

awk '{ print $0, NF }' some_strings.txt

The following screenshot shows how to use this syntax in practice:

Bash count words in each line in file

The output displays each line in the file followed by the total word count in the line.

For example, we can see:

  • The first line has 6 total words.
  • The second line has 2 total words.
  • The third line has 3 total words.

And so on.

Related Tutorials

The following tutorials explain how to perform other common tasks in Bash:

Bash: How to Count Number of Unique Lines in File
Bash: How to Count Number of Characters in String
Bash: How to Count Number of Columns in File

Leave a Reply