number of tokens in bash variable

前端 未结 7 2193
挽巷
挽巷 2020-12-09 08:41

how can I know the number of tokens in a bash variable (whitespace-separated tokens) - or at least, wether it is one or there are more.

7条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-09 09:02

    To count:

    sentence="This is a sentence, please count the words in me."
    words="${sentence//[^\ ]} "
    echo ${#words}
    

    To check:

    sentence1="Two words"
    sentence2="One"
    [[ "$sentence1" =~ [\ ] ]] && echo "sentence1 has more than one word"
    [[ "$sentence2" =~ [\ ] ]] && echo "sentence2 has more than one word"
    

提交回复
热议问题