Sunday, 15 September 2013

Bash- populate an associative array using a loop -



Bash- populate an associative array using a loop -

so have entered , associative array:

47 springgreen2 48 springgreen1 49 mediumspringgreen 50 cyan2 51 cyan1 52 darkred 53 deeppink4

it's part of bash script. i'm looking way create associative array out of this, like

declare -a cols=( [springgreen2]="0;47"...[deeppink4]="0;53" )

i can quite manually.

but want utilize loop populate array cols=( [key]="value" ) loop take 47, 48, 49...53 , out value field, , springgreen2...deeppink4 key field.

i thinking using awk couldn't figure our how isolate 2 fields , utilize each entry populate array.

are intending read file , populate cols array?

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

oh other hand, if have associative array , want "reversed" array:

declare -a rev_cols color in "${!cols[@]}"; rev_cols[${cols[$color]#*;}]=$color done key in "${!rev_cols[@]}"; printf "%s\t%s\n" "$key" "${rev_cols[$key]}"; done

arrays bash awk associative-array

No comments:

Post a Comment