in reply to Replace data in the column of one file with corresponding ones in another file

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
  • Comment on Re: Replace data in the column of one file with corresponding ones in another file
  • Download Code

Replies are listed 'Best First'.
Re^2: Replace data in the column of one file with corresponding ones in another file
by Renyulb28 (Novice) on Jan 27, 2011 at 22:02 UTC
    thank you, but it is giving me this error when I run the script Can't locate File/Slurp.pm in @INC (@INC contains: /etc/perl /usr/local/lib/perl/5.10.1 /usr/local/share/perl/5.10.1 /usr/lib/perl5 /usr/share/perl5 /usr/lib/perl/5.10 /usr/share/perl/5.10 /usr/local/lib/site_perl .) at 2FilesFindReplace.pl line 1.
      The version not relying on File::Slurp would be the following:
      use Tie::File; use strict; my $file1 = 'file1.txt'; my $file2 = 'file2.txt'; open my $fh, $file2 or die "Can't open $file2: $!"; my %hash = map { chomp; my @data = split /\s+/; $data[0] => $data[2]; } <$fh>; 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
      So File::Slurp is not installed.

      Download and install it.