[英]Translating from letters to numbers in bash shell script using tr command
#!/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.我想将字母表翻译成从 0 开始的十进制数字。我尝试了上面提到的代码。 But the output is wrong starting from input 'K'.
但是 output 从输入 'K' 开始是错误的。 For eg, when I enter DAD, the output is 303, but when the input is KILL, the output is 1800 which is giving me wrong one.
例如,当我输入 DAD 时,output 是 303,但是当输入 KILL 时,output 是 1800,这是给我错误的。 K should be translated into 11 but it's taking only 1. My code is not working for the 2 digit decimal numbers.
K 应该被翻译成 11 但它只需要 1。我的代码不适用于 2 位十进制数。
simple bash solution takes alphabetic input on stdin - prints index of each letter 简单的bash解决方案在stdin上采用字母输入-打印每个字母的索引
# 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
A function which will output 1
to 26
for letters a
to z
as well as A
to Z
A function 这将 output
1
到26
对于字母a
到z
以及A
到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 ]"
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.