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?

Answers


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

Need Your Help

Integrating Matlab with C++

matlab opencv visual-c++ image-processing integrate

I need to localize facial landmarks as a part of my research project and planning to use Supervised Descent Method (SDM) for that. Both the C++ and Matlab versions are available at the following si...

Upgrading Spring-security-oauth2 1.0.5.RELEASE to 2.0.5.RELEASE getting 404

spring-security spring-security-oauth2

Getting 404 on authorizationcode and accesstoken service I am Trying to upgrade spring security oauth2 from 1.0.5.Release to 2.0.5.Release.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.