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
or
will do a word count for you.
You can pipe each word to wc:
to store the result in a variable:
to add to the total as you go word by word, do math with this syntax:
The
wc
command is a good bet.where the result is number of lines, words and characters. In a script:
The
declare
built-in casts a variable as an integer here, so that+=
will add rather than append.riffing on Jaypal Singh's answer:
The value of n can be used as an integer in expressions
You are very close. In bash you can use
#
to get the length of your variable.Also, if you want to use
bash
interpreter usebash
instead ofsh
and the first line goes like this -#!/bin/bash
Use this script -