bash - increment variables that contain letters

for those who would like to print incremented letter by execution of a function:

ALPHA=( {A..Z} ) 
alpha_increment () { echo ${ALPHA[${i:-0}]}; ((i++)) ;}

alpha_increment
A
alpha_increment
B
alpha_increment
C

y=b
echo "$y"  # this shows 'b'
y=$(echo "$y" | tr "0-9a-z" "1-9a-z_")
echo "$y"  # this shows 'c'

Note that this does not handle the case where $y = "_" (not sure what you want then, and in any case it'll probably require separate handling), and if $y is more than one character long it'll "increment" all of them (i.e. "10" -> "21", "09g" -> "1ah", etc).


Maybe this can be a solution:

a=({0..9} {a..z} _)
echo ${a[*]}
yc=11
echo ${a[yc]}
((++yc))
echo ${a[yc]}
echo ${a[++yc]}

#Alternative 
declare -A h
# Fill the has point to the next character
for((i=0;((i+1))<${#a[*]};++i)) { h[${a[i]}]=${a[i+1]};}
y=b
echo $y, ${h[$y]}

Output:

0 1 2 3 4 5 6 7 8 9 a b c d e f g h i j k l m n o p q r s t u v w x y z _
b
c
d
b, c

Tags:

Bash