6

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.

2

4 Answers 4

15

You can use wc:

$ wc -w <<< "$str"
3
Sign up to request clarification or add additional context in comments.

Comments

4

Try this:

str='word1 word2 word3'
str=( $str )
echo ${#str[@]}

Comments

1

Using awk:

awk '{print NF}' <<< "$str"
3

Comments

0

wc -w is better, here is another way:

 echo $str |tr " " "\n" |wc -l

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.