shell - add two letters from a variable in bash script -


im working make code take input (word) , output sum of letters in input, letters equal there numeric value- a=1 b=2 c=3 etc,here unfinished code far:-

echo enter word read word let in $word echo $let  *here should take input , calculate output (w+o+r+d = ??) 

here's solution uses associative array map (english) letters ordinal values. note associative arrays require bash 4.0 or higher.

#!/usr/bin/env bash  # declare variables. declare -i sum  # -i declares integer variables declare -a lettervalues # -a declares associative arrays, requires bash 4+ declare letter # regular (string) variable  # create mapping between letters , values # using associative array. # sequence brace expression {a..z} expands 'a b c ... z' # $((++i)) increments variable $i , returns new value. i=0 letter in {a..z};     lettervalues[$letter]=$((++i)) done  # prompt word. read -p 'enter word: ' word  # loop on chars. in word # , sum individual letter values. sum=0 (( = 0; < ${#word}; i++ ));   # extract substring of length 1 (the letter) @ position $i.   # substring indices 0-based.   letter=${word:i:1}   # note due having declared $sum -i,   # surrounding following statement (( ... ))   # optional.   sum+=lettervalues[$letter] done  # output result. echo "sum of letter values: $sum" 

Comments

Popular posts from this blog

node.js - Mongoose: Cast to ObjectId failed for value on newly created object after setting the value -

gradle error "Cannot convert the provided notation to a File or URI" -

ios - Possible to get UIButton sizeThatFits to work? -