S.T.A.L.K.E.R. S.T.A.L.K.E.R. - 4 months ago 19
Linux Question

Print the alphabet in bash

I would like help with the following algorithm in bash (or anything accessible through bash shell): I give a number to some function, and based on that number I obtain a string of alphabet letters. Example:

1 - A
2 - B
....
26 - Z
....
702 - ZZ
703 - AAA


I do not wish to occupy more memory than I need, so approaches such as
for i in {A..Z}
or
echo {A..Z}
or
echo {A..Z}{A..Z}
are not viable here. The closest I've managed to get is to find out how long is the sequence of letters for a particular number through the following expression:

printf %.0f\\n $(echo '(scale=20;l($number)/l(26))+0.5000000000000000001' | bc -l)


After that, I am stuck. A little help?

Answer

Try this script:

#!/bin/bash

alphabet=( {A..Z} )

convertToString(){
    dividend="$1"
    colName=""
    while (( dividend > 0 ))
    do
         mod=$(( (dividend-1)%26 ))
         colName="${alphabet[$mod]}$colName"
         dividend=$(( (dividend-mod)/26 ))
    done
    echo "$colName"
}

convertToString "$1"

Example output:

$ convertToString 1
A

$ convertToString 2
B

$ convertToString 27
AA

$ convertToString 702
ZZ

$ convertToString 703
AAA

$ convertToString 16384
XFD

$ convertToString 1187803
BOOBS