Something like this would work:
# I would greatly appreciate any help. The file that I am trying to # alter is in the format # 23 SNP_A-4293670 0 2713391 # with separation by tabs. The second file is in the format # SNP_A-1780270 ss75925050 rs987435 # with separation by spaces. I want the first file to look like this: # 23 rs###### 0 2713391 # which means that I want the data in second column of the first # file to be replaced with the data in the third column of the second # file if it matches the first column of the second file. Thanks use File::Slurp qw(read_file); use Tie::File; use strict; my $file1 = 'file1.txt'; my $file2 = 'file2.txt'; my %hash = map { chomp; my @data = split /\s+/; $data[0] => $data[2]; } read_file($file2); tie my @array, 'Tie::File', $file1 or die "Can't open $file1: $!"; foreach (@array) { s{^(\S*\s+)(\S+)}{ if (exists $hash{$2}) { print "Replacing $2 with $hash{$2}\n"; $1 . $hash{$2}; } else { print "Can't find $2, not changing\n"; $1 . $2; } }e; }
- Miller

In reply to Re: Replace data in the column of one file with corresponding ones in another file by wind
in thread Replace data in the column of one file with corresponding ones in another file by Renyulb28

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.