关联数组键中的空格,同时在Bash中循环遍历多个数组

时间:2015-03-16 18:42:29

标签: arrays bash for-loop associative-array

在bash中循环遍历多个关联数组时遇到了一些麻烦。

以下是我正在运行的代码:(删除了实际信息)

arrays=("arrayone" "arraytwo")
declare -A arrayone=(["one"]=1 ["two"]=2)
declare -A arraytwo=(["text with spaces"]=value ["more text with spaces"]=differentvalue)
for array in ${arrays[*]} 
 do 
 for key in $(eval echo $\{'!'$array[@]\})   
       do 
       echo "$key"
       done
 done

这很好用,直到我遇到一个包含空格的键值。无论我做什么,我都无法获得有空格的物品来正确对待。

我很感激您对如何使其发挥作用的任何想法。 如果有更好的方法,我会很高兴听到它。我不介意抓住这个并重新开始。它是迄今为止我能够提出的最好的。

谢谢!

1 个答案:

答案 0 :(得分:4)

Bash在4.3中添加了nameref attribute。它允许您将名称专门用于引用另一个名称。在你的情况下,你会做

declare -A assoc_one=(["one"]=1 ["two"]=2)
declare -A assoc_two=(["text with spaces"]=value ["more text with spaces"]=differentvalue)
declare -n array # Make it a nameref
for array in "${!assoc_@}"; do 
    for key in "${!array[@]}"; do
        echo "'$key'"
    done
done

你得到了

'one'
'two'
'text with spaces'
'more text with spaces'

更改名称以保护成语。我的意思是,我更改了数组名称,因此我可以"${!assoc_@}"进行array,而不会使{{1}}成为特殊情况。