I've got an array that contains duplicate items, e.g.
THE_LIST=( "'item1' 'data1 data2'" "'item1' 'data2 data3'" "'item2' 'data4'" )
Based on the above, I want to create an associative array that would assign itemN
as key and dataN
as value.
My code iterates over the list, and assigns key => value like this (the additional function is shortened, as it performs some additional jobs on the list):
function get_items(){ KEY=$1 VALUES=() shift $2 for VALUE in "$@"; do VALUES[${#VALUES[@]}]="$VALUE" done } declare -A THE_LIST for ((LISTID=0; LISTID<${#THE_LIST[@]}; LISTID++)); do eval "LISTED_ITEM=(${THE_LIST[$LISTID]})" get_items "${LISTED_ITEM[@]}" THE_LIST=([$KEY]="${VALUES[@]}") done
when I print the array, I'm getting something like:
item1: data1 data2 item1: data2 data3 item2: data4
but instead, I want to get:
item1: data1 data2 data3 item2: data4
Cannot find a way of merging the duplicate keys as well as removing duplicate values for the key.
What would be the approach here?
UPDATE
The actual code is:
THE_LIST=( "'item1' 'data1 data2'" "'item1' 'data2 data3'" "'item2' 'data4'" ) function get_backup_locations () { B_HOST="$2" B_DIRS=() B_DIR=() shift 2 for B_ITEM in "$@"; do case "$B_ITEM" in -*) B_FLAGS[${#B_FLAGS[@]}]="$B_ITEM" ;; *) B_DIRS[${#B_DIRS[@]}]="$B_ITEM" ;; esac done for ((B_IDX=0; B_IDX<${#B_DIRS[@]}; B_IDX++)); do B_DIR=${B_DIRS[$B_IDX]} ...do stuff here... done } function get_items () { for ((LOCIDY=0; LOCIDY<${#LOCATIONS[@]}; LOCIDY++)); do eval "LOCATION=(${LOCATIONS[$LOCIDY]})" get_backup_locations "${LOCATION[@]}" THE_LIST=([$B_HOST]="${B_DIR[@]}") done | sort | uniq }
when printing the array with:
for i in "${!THE_LIST[@]}"; do echo "$i : ${THE_LIST[$i]}" done
I get
item1: data1 data2 item1: data2 data3 item2: data4
THE_LIST
is already a normal array, so you can't redeclare it as an associative array, and even if you could, you're overwriting it each time in the loop withTHE_LIST=([$KEY]="${VALUES[@]}")
.python
? Complex stuff like this is often easy as hell inpython
.