How to count number of words from String using shell

I want to count number of words from a String using Shell.

Suppose the String is:

input="Count from this String"

Here the delimiter is space ' ' and expected output is 4. There can also be trailing space characters in the input string like "Count from this String ".

If there are trailing space in the String, it should produce the same output, that is 4. How can I do this?


echo "$input" | wc -w

Use wc -w to count the number of words.

Or as per dogbane's suggestion, the echo can be got rid of as well:

wc -w <<< "$input"

If <<< is not supported by your shell you can try this variant:

wc -w << END_OF_INPUT
$input
END_OF_INPUT

You don't need an external command like wc because you can do it in pure bash which is more efficient.

Convert the string into an array and then count the elements in the array:

$ input="Count from this String   "
$ words=( $input )
$ echo ${#words[@]}
4

Alternatively, use set to set positional parameters and then count them:

$ input="Count from this String   "
$ set -- $input
$ echo $#
4