简体   繁体   中英

Merging two arrays in Bash

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:

   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 )

If you don't care about having duplicates, or maintaining indexes, then 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/

Since Bash supports sparse arrays, it's better to iterate over the array than to use an index based on the size.

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")'

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

Here is how I merged two arrays in Bash:

Example arrays:

AR=(1 2 3) BR=(4 5 6)

One Liner:

CR=($(echo ${AR[*]}) $(echo ${BR[*]}))

在 bash 中合并两个数组的一行语句:

combine=( `echo ${array1[@]}` `echo ${array2[@]}` )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM