bash从命令输出生成bidimentional数组

时间:2018-03-31 09:59:04

标签: arrays bash command

使用bash,我试图弄清楚如何从curl命令的输出中填充bidimentional数组。 2列,但行数未知。 让我们说我的名字和电话号码用空格隔开。

$ curl ${url}
Aname 000001
Bname 123456
CCname 000887
Dnname 354632
Xname 007008
...

欢迎各种帮助:) 感谢。

1 个答案:

答案 0 :(得分:0)

也许你可以测试:

#!/bin/bash
declare -A myArray
while read key value; do 
    myArray["$key"]="$value"
done <<< $( curl "$url" )

# examples to use
echo "\$myArray has ${#myArray[@]} elements"
echo "here is the keys: ${!myArray[@]}"
echo "the whole array:"
for key in ${!myArray[@]}; do
    echo "$key => ${myArray[$key]}"
done

用于模拟,您可以使用:

...
done <<< $( cat << "END"
Aname 000001
Bname 123456
CCname 000887
Dnname 354632
Xname 007008
END
)

,结果将是:

$myArray has 5 elements
here is the keys: Aname Xname CCname Bname Dnname
the whole array:
Aname => 000001
Xname => 007008
CCname => 000887
Bname => 123456
Dnname => 354632