jasenmichael
jasenmichael

Reputation: 428

How can I look up each character in each line in a file as a variable name?

in a bash script I have some variables set like this

A=1
B=2

I have a text file called list.txt that contains

AAB
ABA
BBA

also in my script I have

while read LINE
do
    echo "$LINE" | grep -o .
    echo "----"
done < list.txt

my output is

A
A
B
----
A
B
A
----
B
B
A
----

how would I go about getting this as my output?

112
----
121
----
221
----

Upvotes: 0

Views: 38

Answers (3)

Walter A
Walter A

Reputation: 19982

It depends on how fixed your var's are.
(and always postprocess with | sed 's/$/\n----/)
A=1 and B=2 (always)

tr 'AB' '12' < list.txt

Only var's A and B, both 1 character long value.

tr 'AB' $(echo "$A$B") < list.txt

Only var's A and B, values can be longer

sed "s/A/$A/g; s/B/$B/g" list.txt

Var's exist for every letter in the inputfile - See @CharlesDuffy

Or perhaps you have a small set of var's

A=1;B=2;C=3;D=4;E=5;F=6; export A B D C E F
export I="(this is letter i)"
echo "CRAZY SED SOLUTION" | sed -r 's/[A-FI]/${&}/g' | envsubst
# Result
3R1ZY S54 SOLUT(this is letter i)ON

Upvotes: 0

RomanPerekhrest
RomanPerekhrest

Reputation: 92854

Alternative bash + awk solution:

#!/bin/bash

A=1
B=2
awk -v A="$A" -v B="$B" 'BEGIN{ keys["A"]=A; keys["B"]=B }
       { len=split($0,a,"");
       for (i=1;i<=len;i++) printf "%s%s", keys[a[i]], (i==len? "\n---\n":"") }' list.txt

The output:

112
---
121
---
221
---

But the shortest approach (without variables) would be with GNU sed:

sed 'y/AB/12/; s/$/\n---/' list.txt

Upvotes: 1

Charles Duffy
Charles Duffy

Reputation: 295308

A=1
B=2
while IFS= read -r line; do
  for ((idx=0; idx < ${#line}; idx++)); do
    char=${line:$idx:1}
    val=${!char}
    printf '%s' "$val"
  done
  printf '%s\n' '' ----
done <<<$'AAB\nABA\nBBA'

...properly emits as output:

112
----
121
----
221
----

Upvotes: 1

Related Questions