作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我在 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
在我遇到其中包含空格的键值之前,它工作得很好。无论我做什么,我都无法正确处理带有空格的项目。
如果您有任何关于如何实现此功能的想法,我将不胜感激。如果有更好的方法来做到这一点,我很乐意听到。我不介意擦掉这个然后重新开始。这是迄今为止我能想到的最好的。
谢谢!
最佳答案
Bash 添加了 nameref attribute在 4.3。它允许您将一个名称专门作为对另一个名称的引用。在你的情况下,你会做
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
设为特例。
关于arrays - 在 Bash 中循环遍历多个数组时关联数组键中的空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29084566/
我是一名优秀的程序员,十分优秀!