1
    #!/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.

vitr
  • 6,212
  • 8
  • 27
  • 48

1 Answers1

2

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