How to merge two arrays in a zipper like fashion in Bash?

后端 未结 5 1846
野趣味
野趣味 2020-11-29 13:23

I am trying to merge two arrays into one in a zipper like fashion. I have difficulty to make that happen.

array1=(one three five seven)
array2=(two four six          


        
5条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-29 13:36

    This is based on RTLinuxSW's answer, with the improvement from Paused until further notice's comment, which adds support for sparse and associative arrays.

    for index in "${!array1[@]}"; do  # Also, quote indices
        result+=( "${array1[$index]}" "${array2[$index]}" )
    done
    

    After:

    $ echo "${result[@]}"
    one two three four five six seven eight
    $ declare -p result
    declare -a result=([0]="one" [1]="two" [2]="three" [3]="four" [4]="five" [5]="six" [6]="seven" [7]="eight")
    

    This assumes the indices of the two arrays are identical.

提交回复
热议问题