问题
I want to ask about the syntax i use to assign a value of a two dimensional array element to a variable. this is basically what i am trying to do: I have a 2 dimensional array of characters and a string called sub_string that gets the value of a particular element in the array and put it in another string called whole_string
for ((j=1;j<=num_columns;j++)) do
for ((i=1;i<=num_rows;i++)) do
Assigning the value of the element [i,j] in the array matrix to a sub string
whole_string="$whole_String$sub_string"
done
done
I want to know how to assign the value of the array to the sub string i have. thank you
回答1:
With a current bash you can divert an associative array to create multidimensional arrays.
#!/bin/bash
declare -A A # declare associative array A
num_rows=7
num_columns=9
# fill array
for ((j=1;j<=num_rows;j++)) do
for ((i=1;i<=num_columns;i++)) do
A[$j,$i]="$j:$i" # fill with row:column
done
done
# print array
for ((j=1;j<=num_rows;j++)) do
for ((i=1;i<=num_columns;i++)) do
echo -n "${A[$j,$i]} "
done
echo
done
Output (9x7 array):
1:1 1:2 1:3 1:4 1:5 1:6 1:7 1:8 1:9 2:1 2:2 2:3 2:4 2:5 2:6 2:7 2:8 2:9 3:1 3:2 3:3 3:4 3:5 3:6 3:7 3:8 3:9 4:1 4:2 4:3 4:4 4:5 4:6 4:7 4:8 4:9 5:1 5:2 5:3 5:4 5:5 5:6 5:7 5:8 5:9 6:1 6:2 6:3 6:4 6:5 6:6 6:7 6:8 6:9 7:1 7:2 7:3 7:4 7:5 7:6 7:7 7:8 7:9
来源:https://stackoverflow.com/questions/25595249/assigning-the-value-of-an-array-to-a-variable-bash-script