在 Bash 中合并两个数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1986023/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Merging two arrays in Bash
提问by f10bit
I have the following situation, two arrays, let's call them A( 0 1 ) and B ( 1 2 ), i need to combine them in a new array C ( 0:1 0:2 1:1 1:2 ), the latest bit i've come up with is this loop:
我有以下情况,两个数组,我们称它们为 A( 0 1 ) 和 B ( 1 2 ),我需要将它们组合在一个新的数组 C ( 0:1 0:2 1:1 1:2 ) 中,我想出的最新一点是这个循环:
for ((z = 0; z <= ${#A[@]}; z++)); do
for ((y = 0; y <= ${#B[@]}; y++)); do
C[$y + $z]="${A[$z]}:"
C[$y + $z + 1]="${B[$y]}"
done
done
But it doesn't work that well, as the output i get this:
但它并没有那么好,因为我得到的输出是:
0: : : :
In this case the output should be 0:1 0:2 as A = ( 0 ) and B = ( 1 2 )
在这种情况下,输出应为 0:1 0:2,因为 A = ( 0 ) 和 B = ( 1 2 )
采纳答案by Paused until further notice.
Since Bash supports sparse arrays, it's better to iterate over the array than to use an index based on the size.
由于 Bash 支持稀疏数组,因此迭代数组比使用基于大小的索引更好。
a=(0 1); b=(2 3)
i=0
for z in ${a[@]}
do
for y in ${b[@]}
do
c[i++]="$z:$y"
done
done
declare -p c # dump the array
Outputs:
输出:
declare -a c='([0]="0:2" [1]="0:3" [2]="1:2" [3]="1:3")'
回答by Ian Dunn
If you don't care about duplicates, you can concatenate the two arrays in one line with:
如果您不关心重复项,则可以将两个数组连接在一行中:
NEW=("${OLD1[@]}" "${OLD2[@]}")
Full example:
完整示例:
Unix=('Debian' 'Red hat' 'Ubuntu' 'Suse' 'Fedora' 'UTS' 'OpenLinux');
Shell=('bash' 'csh' 'jsh' 'rsh' 'ksh' 'rc' 'tcsh');
UnixShell=("${Unix[@]}" "${Shell[@]}")
echo ${UnixShell[@]}
echo ${#UnixShell[@]}
Credit: http://www.thegeekstuff.com/2010/06/bash-array-tutorial/
信用:http: //www.thegeekstuff.com/2010/06/bash-array-tutorial/
回答by ghostdog74
here's one way
这是一种方法
a=(0 1)
b=(1 2)
for((i=0;i<${#a[@]};i++));
do
for ((j=0;j<${#b[@]};j++))
do
c+=(${a[i]}:${b[j]});
done
done
for i in ${c[@]}
do
echo $i
done
回答by Joel Zamboni
Here is how I merged two arrays in Bash:
这是我在 Bash 中合并两个数组的方法:
Example arrays:
示例数组:
AR=(1 2 3)
BR=(4 5 6)
AR=(1 2 3)
BR=(4 5 6)
One Liner:
一个班轮:
CR=($(echo ${AR[*]}) $(echo ${BR[*]}))
CR=($(echo ${AR[*]}) $(echo ${BR[*]}))
回答by Suresh N S
One line statement to merge two arrays in bash:
在 bash 中合并两个数组的一行语句:
combine=( `echo ${array1[@]}` `echo ${array2[@]}` )