Bows and send Praises to the monks....
Hello:
Can some kind person show me the perl code to the following??
if I had say 30 text files and I wanted to join them on a common column eg 1st column. This would be equilvalent to the "join" tool on a linux box
http://linux.about.com/library/cmd/blcmdl1_join.htm
But instead of limited this to 2 files at a time how to I join 30 files based on 1 column eg first column.
Can some kind person show me the perl code to do this??
Bows and Thanks everyone....
OK I found 2 solutions for joining 2 files not the 30 files I am looking for:
The perl solution below I dont fully understand it all eg whats the variable $pos and $hsize do? can someone improve this code if possible?
and the first solution which is via R which is so simple but not perl...
Thanks everyone for your help in advance
Solution1 using R:
Solution2 using perl:> a<-read.table("a") > b<-read.table("b") > c<-merge(a,b,by.x=1, by.y=1) > c
#!/usr/bin/perl $file1="a"; $file2="b"; $out="test"; $pos=0; $hsize=0; merge_file3($file1, $file2, $out, $pos,$hsize ); sub merge_file3{ my ($file1,$file2,$out,$position,$hsize) = ($_[0],$_[1],$_[2],$_[3],$_ +[4]); print "merging: \n$file1 and \n$file2, to: \n$out\n"; my $OUTSTRING = undef; my $header; my (@file1,@file2); open FILE1, "<$file1" or die; while (<FILE1>){ # if ($.==1){ # $header = $_; # next; # } print "$.\n" if ($.%100000) == 0; chomp; push @file1, [split '\t', $_]; } close FILE1; open FILE2, "<$file2" or die; while (<FILE2>){ # next if $.==1; print "$.\n" if ($.%100000) == 0; chomp; push @file2, [split '\t', $_]; } close FILE2; print "sorting files\n"; my @sortedf1 = sort {$a->[$position] <=> $b->[$position]} @file1; my @sortedf2 = sort {$a->[$position] <=> $b->[$position]} @file2; print "sorted\n"; @file1 = undef; @file2 = undef; #foreach my $line (@file1){print "\t [ @$line ],\n"; } my ($i,$j) = (0,0); while ($i < $#sortedf1 and $j < $#sortedf2){ my $key1 = $sortedf1[$i][$position]; my $key2 = $sortedf2[$j][$position]; if ($key1 eq $key2){ foreach(0..$hsize){ #header size. $sortedf2[$j][$_] = $sortedf1[$i][$_] if $sortedf1[$i][$_] + ne undef; } $i++; $j++; } elsif ( $key1 < $key2){ # push(@sortedf2,[@{$sortedf1[$i]}]); $i++; } elsif ( $key1 > $key2){ $j++; } } #foreach my $line (@sortedf2){print "\t [ @$line ],\n"; } print "outputting to file\n"; open OUT, ">$out"; print OUT $header; print $header; foreach(@sortedf2){ print OUT (join "\t", @{$_})."\n"; print (join "\t", @{$_})."\n"; } close OUT; }
In reply to join mutiple files on first column by david_lyon
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |