Alex
Alex

Reputation: 183

Assign dynamic multidimensional variables

I do have xml, which do have lines like

#<pdfrwt "2"> n_vars code(1) ... code1(2).... code1(n_vars) code2(1) ... code2(n_vars) code3(1) ... code3(n_vars)</pdfrwt>

So actually, depending in the "n_vars" each time, I do have a sequence of numbers which correspond to three classes, ie code1, code2,code3 and for each of these classes I get "n_vars" entries for each one.. So, how can I smartly read the line in bash (ok, this I know ;-) and get to assign a "n_vars" multidimensional variables ie something like

output1[1]=code1(1)
output1[2]=code1(2)
...
output1[n]=code1(n)
and likewise

output2[1]=code2(1)
..
output2[1]=code2(1)

thanks in advance

Alex

Upvotes: 1

Views: 79

Answers (1)

chepner
chepner

Reputation: 531055

You can read the whole line into an array, then take slices of the array.

# hdr gets the first field, n_vars gets the second, and rest gets
# the remaining values
read hdr n_vars rest < file

# Split rest into a proper array
array=( $rest )
# Copy the desired slices from array into the three output arrays.
output1=( "${array[@]:0:n_vars}")
output2=( "${array[@]:n_vars:n_vars}" )
output3=( "${array[@]:2*n_vars:n_vars}" )

Some examples of how to access values:

echo ${output1[0]}    # The first element of output1
echo ${output2[3]}    # The fourth element of output2
echo ${output3[$#output3]}  # The last element of output3
echo "${output1[@]}"   # All the elements of output1

Upvotes: 1

Related Questions