BASH:需要一些帮助与多维关联数组 [英] BASH: need some help with multidimensional associative arrays
问题描述
我试图创建一个多维关联数组,但需要一些帮助。我已审查<一个href=\"http://stackoverflow.com/questions/3020713/how-to-print-bash-varibles-contents-into-two-dimensional-array-bash-shell\">the页面在这个建议的SO回答但它更糊涂了。到目前为止,这里是我有:
I'm trying to create a multidimensional associative array but need some help. I have reviewed the page suggested in this SO answer but it confused me even more. So far here is what I have:
脚本:
#!/bin/bash
declare -A PERSONS
declare -A PERSON
PERSON["FNAME"]='John'
PERSON["LNAME"]='Andrew'
PERSONS["1"]=${PERSON[@]}
PERSON["FNAME"]='Elen'
PERSON["LNAME"]='Murray'
PERSONS["2"]=${PERSON[@]}
for KEY in "${!PERSONS[@]}"; do
TMP="${PERSONS["$KEY"]}"
echo "$KEY - $TMP"
echo "${TMP["FNAME"]}"
echo "${TMP["LNAME"]}"
done
输出:
1 - John Andrew
John Andrew
John Andrew
2 - Elen Murray
Elen Murray
Elen Murray
正如你所看到试图访问$ TMP阵列的具体指标在for循环返回整个阵列。
As you can see trying to access a specific index of the $TMP array in the for loop returns the whole array.
[问]我需要什么,以单独访问FNAME和里面的$ TMP阵LNAME指标做为
循环?
[Q] What do I need to do in order to separately access the "FNAME" and "LNAME" indexes of the $TMP array inside the for
loop?
感谢。
推荐答案
您不能做你想要做的:的bash阵列是一维
You can't do what you're trying to do: bash arrays are one-dimensional
$ declare -A PERSONS
$ declare -A PERSON
$ PERSON["FNAME"]='John'
$ PERSON["LNAME"]='Andrew'
$ declare -p PERSON
declare -A PERSON='([FNAME]="John" [LNAME]="Andrew" )'
$ PERSONS[1]=([FNAME]="John" [LNAME]="Andrew" )
bash: PERSONS[1]: cannot assign list to array member
您可以通过构造一个合适的数组索引字符串假货多面性:
You can fake multidimensionality by composing a suitable array index string:
declare -A PERSONS
declare -A PERSON
PERSON["FNAME"]='John'
PERSON["LNAME"]='Andrew'
i=1
for key in "${!PERSON[@]}"; do
PERSONS[$i,$key]=${PERSON[$key]}
done
PERSON["FNAME"]='Elen'
PERSON["LNAME"]='Murray'
((i++))
for key in "${!PERSON[@]}"; do
PERSONS[$i,$key]=${PERSON[$key]}
done
declare -p PERSONS
# ==> declare -A PERSONS='([1,LNAME]="Andrew" [2,FNAME]="Elen" [1,FNAME]="John" [2,LNAME]="Murray" )'
这篇关于BASH:需要一些帮助与多维关联数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!