How to count number of words from String using shell

后端 未结 6 1565
梦谈多话
梦谈多话 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:13

    To do it in pure bash avoiding side-effects, do it in a sub-shell:

    $ input="Count from this string "
    $ echo $(IFS=' '; set -f -- $input; echo $#)
    4
    

    It works with other separators as well:

    $ input="dog,cat,snake,billy goat,horse"
    $ echo $(IFS=,; set -f -- $input; echo $#)
    5
    $ echo $(IFS=' '; set -f -- $input; echo $#)
    2
    

    Note the use of "set -f" which disables bash filename expansion in the subshell, so if the caller wants expansion it should be done beforehand (Hat Tip @mkelement0).

提交回复
热议问题