Counting characters, words, length of the words and total length in a sentence

后端 未结 7 1950
别跟我提以往
别跟我提以往 2021-02-20 15:08

I have to write a script that takes a sentence and prints the word count, character count (excluding the spaces), length of each word and the length. I know that there exist

7条回答
  •  野的像风
    2021-02-20 15:50

    The wc command is a good bet.

    $ echo "one two three four five" | wc
           1       5      24
    

    where the result is number of lines, words and characters. In a script:

    #!/bin/sh
    
    mystring="one two three four five"
    
    read lines words chars <<< `wc <<< $mystring`
    
    echo "lines: $lines"
    echo "words: $words"
    echo "chars: $chars"
    
    echo -n "word lengths:"
    declare -i nonspace=0
    declare -i longest=0
    for word in $mystring; do
      echo -n " ${#word}"
      nonspace+=${#word}"
      if [[ ${#word} -gt $longest ]]; then
        longest=${#word}
      fi
    done
    echo ""
    echo "nonspace chars: $nonspace"
    echo "longest word: $longest chars"
    

    The declare built-in casts a variable as an integer here, so that += will add rather than append.

    $ ./doit
    lines: 1
    words: 5
    chars: 24
    word lengths: 3 3 5 4 4
    nonspace chars: 19
    

提交回复
热议问题