In this bash tutorial, you will get convert word to number in bash script with examples.
This is implemented using for loop, tr command, switch case in shell script and echo command.
This is tested with following conditions:
- Input should be dynamic input
- This code also needs to convert words to numbers if uppercase exists or combination of upper and lower cases.
Sample Input : One Nine One
Sample Output : 191
1. SOURCE CODE
(wordsnum.sh)
echo "-------------------------------------------"
echo "\t\tWords to Number Conversion"
echo "-------------------------------------------"
echo "Enter the words: "
read str
# convert upper case into lower case for the given string
str=$(echo $str | tr A-Z a-z)
# define the variable
wn=""
# loop the string(word by word processing)
for i in $str
do
# use switch case for each word and convert it to numbers using string combine
case $i in
"zero")
wn=$wn"0"
;;
"one")
wn=$wn"1"
;;
"two")
wn=$wn"2"
;;
"three")
wn=$wn"3"
;;
"four")
wn=$wn"4"
;;
"five")
wn=$wn"5"
;;
"six")
wn=$wn"6"
;;
"seven")
wn=$wn"7"
;;
"eight")
wn=$wn"8"
;;
"nine")
wn=$wn"9"
;;
esac
done
echo "Result: "
echo $wn
2. OUTPUT