2
    #!/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,766
  • 8
  • 30
  • 50
Barani Myat Tun
  • 119
  • 1
  • 2
  • 5
  • 1
    That's because `tr` does a character-by-character translation. You might want to use something like `awk` that gives you better cotnrol. – Some programmer dude Aug 21 '16 at 12:24
  • so how can I translate those alphabets to numbers from 0 to 25? Is there any other way that I can translate?? Would you help? – Barani Myat Tun Aug 21 '16 at 12:26
  • Also, you have a [useless use of `echo`](http://www.iki.fi/era/unix/award.html#echo) there. – tripleee Aug 21 '16 at 12:40
  • 1
    Also http://stackoverflow.com/questions/10067266/when-to-wrap-quotes-around-a-variable – tripleee Aug 21 '16 at 12:41
  • @tripleee `OUT=$(echo $1 | tr $P $C)` is not a useless use of echo. – Petr Skocik Aug 21 '16 at 12:46
  • @PSkocik Then I guess `echo $(echo $(echo $(echo $(echo ...))))` would be even better? – tripleee Aug 21 '16 at 12:48
  • @tripleee Limiting yourself to POSIX (no `<<<`) , how else would you pipe `"$1"` into `tr`? – Petr Skocik Aug 21 '16 at 12:49
  • 1
    That part is fine, but capturing to a variable so that you can print the variable is useless, in isolation. There are certainly situations where you want to print and capture, but this example doesn't seem to be one of them. – tripleee Aug 21 '16 at 12:53

2 Answers2

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
0

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 ]"
}
Roel Van de Paar
  • 2,111
  • 1
  • 24
  • 38