Merging two files

Hi All ,

I have a scenario where we need to combine two files .
Below are the sample files and expected output ,

File 1:

1|ab
1|ac
1|ae
2|ad
2|ac

File 2:

1|xy
1|fc
2|gh
2|ku

Output file :

1|ab|xy
1|ab|fc
1|ac|xy
1|ac|fc
1|ae|xy
1|ae|fc
2|ad|gh
2|ad|ku
2|ac|gh
2|ac|ku

Please help us how this can be done in unix .

this should help you

join -t"|" file1 file2
2 Likes
awk -F "|" 'NR==FNR{X[$1,++Y[$1]]=$2;next}
    {for(i=1;i<=Y[$1];i++){print $1,$2,X[$1,i]}}' OFS="|" file2 file1
1 Like

awk

gawk -F"[|]" '{
if(NR==FNR){
  _[$1]=sprintf("%s,%s",_[$1],$2)
}
else{
  tmp=_[$1]
  n=split(tmp,arr,",")
  for(i=2;i<=n;i++){
    print $0"|"arr
}
}
}
' b a

perl

open my $fh1,"<a.txt" or die "can not open a.txt";
open my $fh2,"<b.txt" or die "can not open b.txt";
my %hash;
while(<$fh2>){
	chomp;
	my @tmp = split("[|]",$_);
	push @{$hash{$tmp[0]}}, $tmp[1];
}
close $fh2;
while(<$fh1>){
	chomp;
	my @tmp = split("[|]", $_);
	my @tmp = @{$hash{$tmp[0]}};
	for(my $i=0;$i<=$#tmp;$i++){
		print $_,"|",$tmp[$i],"\n";
	}
}
close $fh1;

python

dict={}
with open("b.txt","r") as f1:
 for line in f1:
  s=line.replace("\n","")
  items=s.split("|")
  if items[0] in dict:
   dict[items[0]].append(items[1])
  else:
   dict[items[0]]=[items[1]]
with open("a.txt","r") as f2:
 for line in f2:
  s=line.replace("\n","")
  items=s.split("|")
  for i in dict[items[0]]:
   print(s,"|",i,sep="")
1 Like