1

I have 2 lists which I am trying to combine/join/merge using a bash script.

List 1

file1-1
file1-2
file1-3
file1-4

and so on

List 2 contains

file2-1
file2-2
file2-3
file2-4

and so on

I'm try to get an output something like this

file1-1:file2-1
file1-2:file2-1
file1-3:file2-1
file1-4:file2-1
file1-1:file2-2
file1-2:file2-2
file1-3:file2-2
file1-4:file2-2
file1-1:file2-3
file1-2:file2-3
file1-3:file2-3
file1-4:file2-3

and so on

amdixon
  • 3,814
  • 8
  • 25
  • 34
user62597
  • 53
  • 4
  • 1
    Possible duplicate of [How to produce cartesian product in bash?](http://stackoverflow.com/questions/23363003/how-to-produce-cartesian-product-in-bash) – Alessandro Da Rugna Oct 05 '15 at 10:39
  • @AlessandroDaRugna Not really the same as that is creating them from a set of values created in the production part, not making the coupling from files, which requires a different approach than a simple printf statement. – 123 Oct 05 '15 at 11:12

4 Answers4

4

merge.sh

#!/bin/bash

while read line2; do
  while read line1; do
    printf "$line1:$line2\n";
  done < file1.txt;
done < file2.txt;

output

$ ./merge.sh 
file1-1:file2-1
file1-2:file2-1
file1-3:file2-1
file1-4:file2-1
file1-1:file2-2
file1-2:file2-2
file1-3:file2-2
file1-4:file2-2
file1-1:file2-3
file1-2:file2-3
file1-3:file2-3
file1-4:file2-3
file1-1:file2-4
file1-2:file2-4
file1-3:file2-4
file1-4:file2-4
amdixon
  • 3,814
  • 8
  • 25
  • 34
0

Maybe this with GNU Parallel:

parallel -k -a file1 -a file2 echo

file1-1 file2-1
file1-1 file2-2
file1-1 file2-3
file1-1 file2-4
file1-2 file2-1
file1-2 file2-2
file1-2 file2-3
file1-2 file2-4
file1-3 file2-1
file1-3 file2-2
file1-3 file2-3
file1-3 file2-4
file1-4 file2-1
file1-4 file2-2
file1-4 file2-3
file1-4 file2-4

Or this:

parallel -k -a file2 -a file1 echo {2}:{1}

file1-1:file2-1
file1-2:file2-1
file1-3:file2-1
file1-4:file2-1
file1-1:file2-2
file1-2:file2-2
file1-3:file2-2
file1-4:file2-2
file1-1:file2-3
file1-2:file2-3
file1-3:file2-3
file1-4:file2-3
file1-1:file2-4
file1-2:file2-4
file1-3:file2-4
file1-4:file2-4
Mark Setchell
  • 191,897
  • 31
  • 273
  • 432
  • 1
    They want them the other way round, obviously a simple fix but just thought I'd mention it. – 123 Oct 05 '15 at 13:13
  • 1
    @999999999999999999999999999999 Picky! ;-) Thank you. – Mark Setchell Oct 05 '15 at 13:16
0

join on a fake field and trim it afterwards

join -t: <(sed 's/^/:/' file1) <(sed 's/^/:/' file2) | cut -c2-
karakfa
  • 66,216
  • 7
  • 41
  • 56
0

This alternative uses awk:

awk 'BEGIN {OFS=":"}
     { 
        while(getline line < "file1"){  print line,$0  }
     } 
     close("file1")
' file2
vagoberto
  • 2,372
  • 20
  • 30