2

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
  • 698,132
  • 130
  • 858
  • 1,229
MOHAMED
  • 38,769
  • 51
  • 148
  • 252

4 Answers4

9

You can use wc:

$ wc -w <<< "$str"
3
fedorqui
  • 252,262
  • 96
  • 511
  • 570
4

Try this:

str='word1 word2 word3'
str=( $str )
echo ${#str[@]}
Martin Dinov
  • 8,480
  • 2
  • 27
  • 40
1

Using awk:

awk '{print NF}' <<< "$str"
3
anubhava
  • 713,503
  • 59
  • 514
  • 593
0

wc -w is better, here is another way:

 echo $str |tr " " "\n" |wc -l
BMW
  • 38,908
  • 11
  • 90
  • 109