gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 09:25:52 26 4
gpt4 key购买 nike

我在 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com