Left Join in Unix based on Key?

So I have 2 files:

File 1:

111,Mike,Stipe
222,Peter,Buck
333,Mike,Mills

File 2:

222,Mr,Bono
444,Mr,Edge

I want output to be below, where 222 records joined and all none joined records still in output

111,Mike,Stipe
222,Peter,Buck,Mr,Bono
333,Mike,Mills
444,Mr,Edge

thanks in advance.

Hi stack,

Using 'Perl':

$ cat file1
111,Mike,Stipe
222,Peter,Buck
333,Mike,Mills
$ cat file2
222,Mr,Bono
444,Mr,Edge
$ cat stack.pl
use warnings;
use strict;

die qq[Usage: perl $0 file1 file2\n] if @ARGV != 2;

my ( %code );

while ( <> ) {
        chomp;
        my @f = split /,/, $_, 2;
        next if @f != 2;
        push @{ $code{ $f[0] } }, $f[1];
}

for ( sort keys %code ) {
        printf qq[%d,%s\n],
                $_,
                join ",", @{ $code{ $_ } };
}
$ perl stack.pl file1 file2
111,Mike,Stipe
222,Peter,Buck,Mr,Bono
333,Mike,Mills
444,Mr,Edge

Regards,
Birei

1 Like

thanks so much it works. any way to do this with awk or sed?

You could certainly do it in awk, but it's easier to just use join:

join -t, -j1 -a 1 -a 2 file1 file2

(unless I'm forgetting something, which I usually do :p)

1 Like

thanks!! yes I was missing -a option which is what I needed!! thanks.