rami
rami

Reputation: 11

How to associate a digit with each letter?

I want to set a number for each alphabetic character. I normally get what I want when I do this

#!/bin/bash
A=4
B=6
c=5 
echo $A$A$B$c

but I need an easier way than putting $ before each letter.

Upvotes: 0

Views: 211

Answers (2)

William Pursell
William Pursell

Reputation: 212268

Use tr to apply the translation map. For the case in your example:

echo AABc | tr ABc 465

This won't work if you are trying to use 2 digit numbers (eg, if you are trying to replace the entire alphabet with 0-25 or 1-26), but it's not at all clear what you are actually trying to do.

Upvotes: 1

Zilicon
Zilicon

Reputation: 3860

I think your best option would be to use an associative array. That is of course if you don't have portability problems and are using bash version 4 and up.
You can do it like this:

#!/bin/bash

set -e

declare -A map
map[A]=4
map[B]=6
map[C]=5

STR="ABC"

echo -n "${STR}" | while IFS= read -r -n1 char; do
    echo -n ${map[${char}]}
done
echo

If you prefer creating a variable for each letter, like shown in your example, you can use the eval command:

#!/bin/bash

set -e

A=4
B=6
C=5

STR="ABC"

echo -n "${STR}" | while IFS= read -r -n1 char; do
    eval "echo -n \$${char}"
done

Upvotes: 1

Related Questions