Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
185 views
in Technique[技术] by (71.8m points)

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 )

question from:https://stackoverflow.com/questions/1986023/merging-two-arrays-in-bash

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...