How to count number of words from String using shell

后端 未结 6 1554
梦谈多话
梦谈多话 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:11
    echo "$input" | wc -w
    

    Use wc -w to count the number of words.

    Or as per dogbane's suggestion, the echo can be got rid of as well:

    wc -w <<< "$input"
    

    If <<< is not supported by your shell you can try this variant:

    wc -w << END_OF_INPUT
    $input
    END_OF_INPUT
    
    0 讨论(0)
  • 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).

    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2020-12-16 10:17
    echo "$input" | awk '{print NF}'
    
    0 讨论(0)
  • 2020-12-16 10:19

    Try the following one-liner:

    echo $(c() { echo $#; }; c $input)
    

    It basically defines c() function and passes $input as the argument, then $# returns number of elements in the argument separated by whitespace. To change the delimiter, you may change IFS (a special variable).

    0 讨论(0)
  • 2020-12-16 10:22

    I'll just chime in with a perl one-liner (avoiding 'useless use of echo'):

    perl -lane 'print scalar(@F)' <<< $input
    
    0 讨论(0)
提交回复
热议问题