I can think of one quick-and-dirty solution that would work for small files but wouldn't scale up well to large ones, so I'll assume the files might be large. First, turn file2 into a hash, with the first part of each line as the key and the second part as the value. Then, loop through the lines of file1, check to see if each "word" is in the hash, and append its value to it if it is. Something like this:

#!/usr/bin/env perl use 5.010; use warnings; use strict; my %h; open my $fd2, '<', 'file2' or die $!; while (<$fd2>){ chomp; my($k, $v) = split /_/; $h{$k} = $v; } open my $fd1, '<', 'file1' or die $!; while (<$fd1>){ s/(\w+)/$h{$1}?"${1}_$h{$1}":$1/ge; print; }

Oh, and here's the quick and dirty solution, which reads all of file1 into memory:

perl -e '$f1=`cat file1`;open $f2,"<","file2";while(<$f2>){chomp;($k,$ +v)=split "_";$f1=~s/$k/${k}_$v/g;}print $f1;'

Aaron B.
Available for small or large Perl jobs and *nix system administration; see my home node.


In reply to Re: search contents of one file and replace with contents of another to make a new file by aaron_baugher
in thread SOLVED!!!: search contents of one file and replace with contents of another to make a new file by vcorby

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.