How to count number of words from String using shell

后端 未结 6 1562
梦谈多话
梦谈多话 2020-12-16 09:44

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

Suppose the String is:

input=\"Count from this String\"

Here the delimit

6条回答
  •  佛祖请我去吃肉
    2020-12-16 10:17

    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
    

提交回复
热议问题