vinnitu
vinnitu

Reputation: 4364

How to convert numbers to the first letters of the alphabet?

I have a file with content like

12345

I need to convert this kind of strings like this:

"0"->"a"
"1"->"b"
...
"9"->"j"

So, 12345 should result in abcde. I want to achieve this via the shell (bash). What is the best way to do this?

Upvotes: 10

Views: 14636

Answers (7)

Eduardo Perez
Eduardo Perez

Reputation: 573

Easy method in bash if you're okay with using arrays.

alphabet=({A..Z})
number=8
letter="${alphabet[$number]}"

With this method, A will be 0, B will be 1, etc.

If you instead want A to be mapped to 1, just change the array value to this.

alphabet=('' {A..Z})

Upvotes: 2

Roel Van de Paar
Roel Van de Paar

Reputation: 2228

Here is a solution which works for all letters of the alphabet (with thanks):

inputnr=1  # a
declare -i i=$[ 97-1+${inputnr} ]
c=$(printf \\$(printf '%03o' $i))
echo "char:" $c
inputnr=26  # z
declare -i i=$[ 97-1+${inputnr} ]
c=$(printf \\$(printf '%03o' $i))
echo "char:" $c

Upvotes: 0

Eugene Yarmash
Eugene Yarmash

Reputation: 149823

There's more than one way to do it:

perl -lnaF -e 'print map chr($_+97), @F' file
abcdefghij

Upvotes: 1

Jonathan Leffler
Jonathan Leffler

Reputation: 754030

In any shell, you could use:

echo "$string" | tr 0123456789 abcdefghij

Or, in Bash and without a pipe:

tr 0123456789 abcdefghij <<< "$string"

(where the double quotes might not be necessary, but I'd use them to be sure).

Upvotes: 17

frankc
frankc

Reputation: 11473

tr 0123456789 abcdefghij < filename

Upvotes: 1

akira
akira

Reputation: 6117

 echo 12345 | tr '[0-9]' '[a-j]'

Upvotes: 9

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798746

With sed's map operator.

sed 'y/12345/hWa!-/' <<< '2313134'

Upvotes: 2

Related Questions