[英]Spaces in Associative Array Keys while looping through multiple arrays in Bash
我在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在4.3中添加了nameref屬性 。 它允許您將名稱專門用於引用另一個名稱。 在你的情況下,你會這樣做
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
作為特殊情況。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.