Merging two arrays in Bash

后端 未结 5 1655
梦如初夏
梦如初夏 2020-12-13 13:39

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 u

相关标签:
5条回答
  • 2020-12-13 14:25

    One line statement to merge two arrays in bash:

    combine=( `echo ${array1[@]}` `echo ${array2[@]}` )
    
    0 讨论(0)
  • 2020-12-13 14:29

    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[*]}))

    0 讨论(0)
  • 2020-12-13 14:33

    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")'
    
    0 讨论(0)
  • 2020-12-13 14:41

    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/

    0 讨论(0)
  • 2020-12-13 14:44

    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
    
    0 讨论(0)
提交回复
热议问题