Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 )

like image 607
f10bit Avatar asked Dec 31 '09 16:12

f10bit


1 Answers

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/

like image 181
Ian Dunn Avatar answered Sep 30 '22 14:09

Ian Dunn