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

mydreamadsl picture mydreamadsl · Jan 5, 2012 · Viewed 76.2k times · Source

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 wc -m to counter number of characters in the word, but how to make use of it in script?

#!/bin/bash

mystring="one two three test five"
maxlen=0;
for token in $mystring; do
  echo -n "$token: ";
  echo -n $token | wc -m;
    if [ ${#token} -gt $maxlen ]; then 
      maxlen=${#token}; fi;
done

echo "--------------------------";
echo -n "Total words: ";
echo "$mystring" | wc -w;
echo -n "Total chars: ";
echo "$mystring" | wc -m;
echo -n "Max length: "; 
echo $maxlen

Answer

jcomeau_ictx picture jcomeau_ictx · Jan 5, 2012

riffing on Jaypal Singh's answer:

jcomeau@intrepid:~$ mystring="one two three four five"
jcomeau@intrepid:~$ echo "string length: ${#mystring}"
string length: 23
jcomeau@intrepid:~$ echo -n "lengths of words: "; i=0; for token in $mystring; do echo -n "${#token} "; i=$((i+1)); done; echo; echo "word count: $i"
lengths of words: 3 3 5 4 4 
word count: 5
jcomeau@intrepid:~$ echo -n "maximum string length: "; maxlen=0; for token in $mystring; do if [ ${#token} -gt $maxlen ]; then maxlen=${#token}; fi; done; echo $maxlen
maximum string length: 5