Open the 2nd file and make a hash of the Gene to the column 2. Then read each line from file1, look up the gene's value in the hash, then add that to the end of the line from file1. It is not necessary to know how many columns are in file1 or even file2. Column 1 in file1 matters. Both Column 1 and Column2 in file2 matter.
#!/usr/bin/perl -w use strict; my %col2; #gene in column 1 to special column 2 my ($file1, $file2) = @ARGV; if (@ARGV != 2) { print "some usage here\n"; exit(); }; open (my $two_cols, '<', $file2) or die "unable to open $file2 $!"; open (my $big_file, '<', $file1) or die "unable to open $file1 $!"; %col2 = map{ s/\s+$//; #chomp + zap trailing white space my ($gene, $v) = split(/\t/,$_,3); }<$two_cols>; while (<$big_file>) { s/\s+$//; my ($gene, $rest) = split(/\t/,$_,2); if (my $lastcol = $col2{$gene}) { print "$gene\t$rest\t$lastcol\n"; } else { warn "$gene not found in $file2\n"; } } __END__ C:\TEMP>type f1.txt gene1 1234 78975 gene13 9876 ldlgfjk C:\TEMP>type f2.txt gene1 abc gene13 xyz C:\TEMP>update.pl f1.txt f2.txt gene1 1234 78975 abc gene13 9876 ldlgfjk xyz

In reply to Re: Adding a particular column from one file to a second file by Marshall
in thread Adding a particular column from one file to a second file by ZWcarp

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.