4

I have the following string which contains words separated by spaces

str="word1 word2 word3"

How to count the number of words?

I do not want to use a for loop with counter. I want to do it in one command.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
MOHAMED
  • 41,599
  • 58
  • 163
  • 268

4 Answers4

13

You can use wc:

$ wc -w <<< "$str"
3
fedorqui
  • 275,237
  • 103
  • 548
  • 598
4

Try this:

str='word1 word2 word3'
str=( $str )
echo ${#str[@]}
Martin Dinov
  • 8,757
  • 3
  • 29
  • 41
1

Using awk:

awk '{print NF}' <<< "$str"
3
anubhava
  • 761,203
  • 64
  • 569
  • 643
0

wc -w is better, here is another way:

 echo $str |tr " " "\n" |wc -l
BMW
  • 42,880
  • 12
  • 99
  • 116