i need to combine ARRAY1
and ARRAY2
into an associative array like ARRAY
. i'm using this code:
mapfile -t ARRAY1 < <(/bin/awk '{ print $ 1 }' /output/gen_branch)
mapfile -t ARRAY2 < <(/bin/awk '{ print $ 6 }' /output/gen_code )
declare -A ARRAY
for ((i=0; $i<${#ARRAY1[@]}; i++))
do
ARRAY+=( ["${ARRAY1[i]}"] = "${ARRAY2[i]}" )
done
##added this loop to check output
for value in "${!ARRAY[@]}"
do
echo "branch: $value"
echo "code: ${ARRAY[$value]}"
done
i expect something like this to use them in other parts of bash (it is important that the value of first element of ARRAY1
be the first element of ARRAY2
and so on) :
ARRAY1=( b1 b2 b3 )
ARRAY2=( c1 c2 c3 )
ARRAY= ( [b1]=c1 [b2]=c2 [b3]=c3 )
but when i run my code i get this error:
line 7: ARRAY: [b1]: must use subscript when assigning associative array
line 7: ARRAY: =: must use subscript when assigning associative array
line 7: ARRAY: c1: must use subscript when assigning associative array
(and it goes on like this for every entry)
i think i'm doing it all wrong on line 7.what should i do to fix this?
=
awk
?$
is an operator like any other inawk
, there's no problem having spaces around it, not any more than around+
or*
.awk
is a tool designed for text processing and with associative array support and is much more efficient at it than a shell. So, unless you need to run some commands on the elements of that associative array (a shell is the tool to run other commands,awk
does invoke a shell to run other commands for instance), it would make more sense to useawk
.