Dearest Monks,
I am trying to replace the text in file #1 with the text in file #2 to make file #3. I would like to do so based on the identity between the text in file #1 and the text before the underscore (_) in file #2 to make file #3. The basic idea is to be able to add the content after the underscore (which is indicated in file #2) into each entry of file #1, but I want to maintain the commas and line breaks found in file #1 so that it can be read into another program.
Here are smaller versions of my files:
File 1 (1.txt):
IIY86TY04J1FRV,IIY86TY04IIJKA,IIY86TY04JGLTI IIY86TY04JH3LU IIY86TY04I9BQV,IIY86TY04JEKGS,IIY86TY04JWBSL,IIY86TY04JUIVK IIY86TY04JUW5G,IIY86TY04JAWV0
File 2 (2.txt):
IIY86TY04J1FRV_HG1 IIY86TY04IIJKA_HG3 IIY86TY04JGLTI_HG4 IIY86TY04JH3LU_HG1 IIY86TY04I9BQV_crop4 IIY86TY04JEKGS_HG1 IIY86TY04JWBSL_HG4 IIY86TY04JUIVK_HG4 IIY86TY04JUW5G_HG2 IIY86TY04JAWV0_HG3
I want to make File 3 (3.txt):
IIY86TY04J1FRV_HG1,IIY86TY04IIJKA_HG3,IIY86TY04JGLTI_HG4 IIY86TY04JH3LU_HG1 IIY86TY04I9BQV_crop4,IIY86TY04JEKGS_HG1,IIY86TY04JWBSL_HG4,IIY86TY04JU +IVK_HG4 IIY86TY04JUW5G_HG2,IIY86TY04JAWV0_HG3
Based on a similar post, I thought I could do the following (please excuse my child-like annotations):
#!/usr/local/bin/perl use warnings; use strict; my $f1 = '1.txt'; # set up files 1 through 3 my $f2 = '2.txt'; my $f3 = '3.txt'; my (@strings, $text); open (FH, $f1) || die; # open file 1 in a file handle chomp(@strings = <FH>); # take off the line breaks open (FH, $f2) || die; # open file 2 in a file handle $text = join '', <FH>; # joins files 1 and 2? - I don't think I wa +nt to do this... $text =~ s/\Q$_\E/$f3/g for @strings; # this is the problem spot, +I think... open (FH, ">$f3") || die; print FH $text; close FH;
but obviously not because when I do I get this for 3.txt:
IIY86TY04J1FRV_HG1 IIY86TY04IIJKA_HG3 IIY86TY04JGLTI_HG4 3.txt_HG1 IIY86TY04I9BQV_crop4 IIY86TY04JEKGS_HG1 IIY86TY04JWBSL_HG4 IIY86TY04JUIVK_HG4 IIY86TY04JUW5G_HG2 IIY86TY04JAWV0_HG3
Any ideas?
And many thanks in advance.
Vanessa
THANK YOU PERL MONKS!! YOU ARE AWESOME!!
Here is another version that works too. I also switched around the order of where the information after the underscore was placed in the output file...
use warnings; use strict; my $f1 = '1.txt'; # file that needs the treatments added on my $f2 = '2.txt'; # file that has all of the treatments and an under +score my $f3 = '3.txt'; # output file my %ids; my $fh; open $fh, '<', $f2 or die; while (<$fh>) { chomp; my ($name, $id) = split /_/; $ids{$name} = $id; } close $fh; open my $fho, '>', $f3 or die; open $fh, '<', $f1 or die; while (<$fh>) { chomp; my @names = split /,/; foreach my $name (@names) { $name = $name . '_' . $ids{$name}; } my $line = join(',', @names); print $fho $line, "\n"; } close $fh; close $fho;
In reply to SOLVED!!!: search contents of one file and replace with contents of another to make a new file by vcorby
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |