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.

2
  • Use a while read loop Commented Nov 11, 2014 at 1:49
  • key=']'; declare -A aarr=( ["$key"]=value ) or declare -A aarr=( [\]]=value ) gives bash: []]=value: bad array subscript Commented Nov 17, 2021 at 7:08

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

6 Comments

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.
More details please. What does the script look like. Please edit your question.
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.
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
the '-a' needs to be '-A'
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.