Reputation: 109
#!/bin/bash
P="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
C="012345678910111213141516171819202122232425"
OUT=`echo $1 | tr $P $C`
echo $OUT
I would like to translate the alphabets into decimal numbers starting from 0. I tried like the code I mentioned above. But the output is wrong starting from input 'K'. For e.g, when I enter DAD, the output is 303, but when the input is KILL, the output is 1800 which is giving me wrong one. K should be translated into 11 but it's taking only 1. My code is not working for the 2 digit decimal numbers.
Upvotes: 2
Views: 2930
Reputation: 2228
A function which will output 1
to 26
for letters a
to z
as well as A
to Z
reverse_nth_letter(){ # With thanks, https://stackoverflow.com/a/39066314/1208218
P=({a..z})
declare -A C
for((i=0;i<${#P[*]};++i)){ C[${P[i]}]=$i; }
LETTER="$(echo "${1}" | tr '[:upper:]' '[:lower:]')"
echo -n "$[ ${C[${LETTER}]} + 1 ]"
}
Upvotes: 1
Reputation: 827
simple bash solution takes alphabetic input on stdin - prints index of each letter
# fill P array of a-z
P=({a..z})
# fill C map of a-z to index
declare -A C
for((i=0; i < ${#P[*]}; ++i)); do
C[${P[i]}]=$i
done
# lowercase input
typeset -l line
while IFS= read -r line; do
# print index of each letter in line
for((i=0; i<${#line}; ++i)); do
echo -n "${C[${line:i:1}]}"
done
echo
done
Upvotes: 2