2

So I have this to be entered into and associative array:

47 SPRINGGREEN2
48 SPRINGGREEN1
49 MEDIUMSPRINGGREEN
50 CYAN2
51 CYAN1
52 DARKRED
53 DEEPPINK4

It's part of a bash script. I'm looking for a way to make an associative array out of this, so it would look like

    declare -A cols=( [SPRINGGREEN2]="0;47"...[DEEPPINK4]="0;53" )

I can do that quite easily manually.

But I want to use a for loop to populate the array cols=( [KEY]="vALUE" ) For loop will take 47, 48, 49...53 and out it into VALUE field, and SPRINGGREEN2...DEEPPINK4 into the key field.

I was thinking using awk but couldn't figure our how to isolate the two fields and use each entry to populate the array.

Bruce Strafford
  • 173
  • 4
  • 15
  • Use a [`while read`](http://stackoverflow.com/questions/1521462/looping-through-the-content-of-a-file-in-bash/1521498#1521498) loop – that other guy Nov 11 '14 at 01:49
  • `key=']'; declare -A aarr=( ["$key"]=value )` or `declare -A aarr=( [\]]=value )` gives `bash: []]=value: bad array subscript` – Fravadona Nov 17 '21 at 07:08

1 Answers1

8

Are you intending to read from the file and populate the cols array?

declare -a cols
while read num color; do
    cols[$num]=$color
done < file.txt
for key in "${!cols[@]}"; do printf "%s\t%s\n" "$key" "${cols[$key]}"; done

Oh the other hand, if you already have the associative array and you also want a "reversed" array:

declare -a rev_cols
for color in "${!cols[@]}"; do
    rev_cols[${cols[$color]#*;}]=$color
done
for key in "${!rev_cols[@]}"; do printf "%s\t%s\n" "$key" "${rev_cols[$key]}"; done
glenn jackman
  • 238,783
  • 38
  • 220
  • 352
  • is there a way to populate the array if the set of keys and values are on the same file as the array (bash script in this case) Basically I want to input those keys, values into an array and then use that array for something else. I have about 255 keys, values I need to put into an associative array and I don't want to do it manually. – Bruce Strafford Nov 11 '14 at 02:15
  • More details please. What does the script look like. Please edit your question. – glenn jackman Nov 11 '14 at 02:19
  • I haven't gotten that far. What I know is I want to enter 255 lines of Key and Values and enter them into an associative array. What I want to do with that array? It's basically going to be used to print input/strings into random colored characters. – Bruce Strafford Nov 11 '14 at 02:46
  • How about this: create a separate bash script that contains only the variable declaration. When you write a script that wants to use colours, you can `source /path/to/colors.bash` – glenn jackman Nov 11 '14 at 03:51
  • It would work, except it's for an assignment, and including a source file would be a hassle. – Bruce Strafford Nov 11 '14 at 19:17
  • the '-a' needs to be '-A' – NathanTempelman Jul 13 '22 at 00:46