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

后端 未结 5 1835
野趣味
野趣味 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:31

    < Update >This below solution is designed to work with data delimited by newlines: each value to be loaded into the array on a separate line in each file. Works perfectly as written, but if your data is organized differently, please see @Socowi 's alternative using paste with printf in the comments. Much thanks to @Socowi for both raising the issue & offering a workaround for data delimited in other ways! < / Update >

    Here's another solution to interleave data from (2) arrays which are populated with data delimited by newlines in separate files. This solution uses paste, echo & xargs:

    Array Data: I feed files to arrays because I like to disaggregate data from code. Following files with each value delimited by a newline will be consumed by readarray:

    test1.txt:

    one
    three
    five
    seven
    

    test2.txt:

    two
    four
    six
    eight
    

    Put it all together:

    #!/bin/bash
    
    readarray arrayTest1 < /root/test1.txt
    readarray arrayTest2 < /root/test2.txt
    
    paste <( echo "${arrayTest1[*]}" ) <( echo "${arrayTest2[*]}" ) | xargs
    

    Output:

    one two three four five six seven eight
    

提交回复
热议问题