I'm trying to write a script in bash using an associative array.
I have a file called data
:
a,b,c,d,e,f
g,h,i,j,k,l
The following script:
oldIFS=${IFS}
IFS=","
declare -A assoc
while read -a array
do
assoc["${array[0]}"]="${array[@]}"
done
for key in ${!assoc[@]}
do
echo "${key} ---> ${assoc[${key}]}"
done
IFS=${oldIFS}
gives me
a ---> a b c d e f
g ---> g h i j k l
I need my output to be:
a b ---> c d e f
g h ---> i j k l
oldIFS=${IFS}
IFS=","
declare -A assoc
while read -r -a array
do
assoc["${array[0]} ${array[1]}"]="${array[@]:2}"
done < data
for key in "${!assoc[@]}"
do
echo "${key} ---> ${assoc[${key}]}"
done
IFS=${oldIFS}
data:
a,b,c,d,e,f
g,h,i,j,k,l
Output:
a b ---> c d e f
g h ---> i j k l
Uses Substring Expansion
here ${array[@]:2}
to get substring needed as the value of the assoc
array. Also added -r
to read
to prevent backslash to act as an escape character.
Improved based on @gniourf_gniourf's suggestions:
declare -A assoc
while IFS=, read -r -a array
do
((${#array[@]} >= 2)) || continue
assoc["${array[@]:0:2}"]="${array[@]:2}"
done < data
for key in "${!assoc[@]}"
do
echo "${key} ---> ${assoc[${key}]}"
done
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With