关联bash中数组中一个键的多个值 [英] associate multiple values for one key in array in bash
问题描述
我有一个文本文件,如下所示:
I have a text file that looks like:
1 aaaa
2 bbbb
3 cccc
4 dddd
2 eeee
2 ffff
4 gggg
我想将它们映射到某种关联数组中,以便访问例如与键2关联的所有值和与键4关联的所有值,等等:
I would like to map these into some sort of associative array so that I can access, for example, all the values associated with the key 2 and all the values associated with the key 4, etc.:
1->aaaa
2->bbbb,eeee,ffff
3->cccc
4->dddd,gggg
我无法弄清楚如何使用"declare -A MYMAP"来做到这一点.有一些简单的方法可以做到这一点吗?
I haven't been able to figure out how to do this with 'declare -A MYMAP'. Is there some easy way to do this?
--------更新--------
--------update--------
我的键/值对实际上看起来像这样:
my key/value pairs look like this actually:
bb126.B1 bb126.1.ms.01
bb126.B2 bb126.1.ms.02
bb126.B3 bb126.1.ms.03
bb126.B4 bb126.1.ms.04
推荐答案
这是使用关联数组:
# store
declare -A array # this is the only update
while read key value; do
array[$key]="${array[$key]}${array[$key]:+,}$value"
done < file
# print
for key in "${!array[@]}"; do echo "$key->${array[$key]}"; done
说明
array[$key]="${array[$key]}${array[$key]:+,}$value"
保存array[$key]
中以,
分隔的每个$value
:
-
${array[$key]}
保存以前的值(如果有). -
${array[$key]:+,}
如果有以前的值,则会添加,
. -
$value
添加新的读取值.
${array[$key]}
save previous value(s) (if any).${array[$key]:+,}
adds a,
if there's a previous value.$value
adds the new read value.
for key in "${!array[@]}"; do echo "$key->${array[$key]}"; done
打印与每个$key
相关的值.
来自 man bash
:
$ {parameter:+ word}
如果参数为null或未设置,则不替换任何内容,否则替换word的扩展名.
${parameter:+word}
If parameter is null or unset, nothing is substituted, otherwise the expansion of word is substituted.
$ {!name [@]}
$ {!name [*]}
如果name是数组变量,则扩展到name中分配的数组索引(键)列表.如果name不是数组,则在name设置为0时扩展为0,否则为null.如果使用"@",并且扩展名出现在双引号中,则每个键都会扩展为一个单独的单词.
${!name[@]}
${!name[*]}
If name is an array variable, expands to the list of array indices (keys) assigned in name. If name is not an array, expands to 0 if name is set and null otherwise. When ‘@’ is used and the expansion appears within double quotes, each key expands to a separate word.
示例
$ cat file
1 aaaa
2 bbbb
3 cccc
4 dddd
2 eeee
2 ffff
4 gggg
$ ./script.sh
1->aaaa
2->bbbb,eeee,ffff
3->cccc
4->dddd,gggg
这篇关于关联bash中数组中一个键的多个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!