I have two scalar values in the form of columns:
% echo $key
hom
doc
fam
echo $val
'home'
'Documents'
'Family'
and I want to create associative array from them.
I'm aware about the method of creation the associative array like below:
declare -A my_assoc_arr
my_assoc_arr=(hom home doc Documents fam Family)
But what is the easiest method create an associative array by digesting $key
and $val
in the form as I have them (scalar, column-like)? Is there any other association syntax, or I need to put my effort into reshuffling $key
and $val
to the association syntax above?
CodePudding user response:
You probably need a loop, but it's not too messy. You'll just use two read
commands to read a line from each string at one time.
typeset -A arr
while IFS= read -u 3 -r k
IFS= read -u 4 -r v
do
arr[$k]=$v
done 3<<< $key 4<<< $val
The first read
reads from file descriptor 3 (which is redirected from a here string created from $key
, the second from file descriptor 4 (likewise redirected from $val
).
$ typeset -p arr
typeset -A arr=( [doc]=Documents [fam]=Family [hom]=home )
(This assumes key
and val
have the same number of lines. I don't want to go down the rabbit hole of dealing with the alternative, which makes you decide what to do with leftover keys or values.)