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
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