0

This question already has an answer here:

I have a file first.html which contains the following code:

<tr>
<td class="headerValue">One</td>
</tr>
<tr>
<td class="headerValue">Two</td>
</tr>

Now I have another file second.txt which contains some values like:

hahaha
hehehe

I want to replace the value in each occurence of "headerValue" with the value from the second file.

Eg. after replacement first.html will become

<tr>
<td class="headerValue">hahaha</td>
</tr>
<tr>
<td class="headerValue">hehehe</td>
</tr>

The data from file second.txt is unrelated to the data from file first.txt

marked as duplicate by G-Man, Archemar, lcd047, Anthon, roaima Jul 17 '15 at 14:38

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

0

Here is a possible answer. I used perl though. It does not check for blank lines in the second file. And the substitution is hard coded.

#!/usr/bin/perl
#
use strict;

# subroutine to load a test file into an array
sub load{
   my $file = shift;
   open my $in, "<", $file or die "unable to open $file : $!";
   my @data = <$in>;
   chomp @data;
   foreach (@data) { s/\cM//g;}
   return @data;
}


my $first = shift || die "usage: $0 [first] [second]\n";
my @first_data = &load($first);
my $second = shift || die "usage: $0 [first] [second]\n";
my @second_data = &load($second);

my $i = 0;
foreach( @first_data )
{
    if( s{(<td class="headerValue">)(.*?)(</td>)}{$1$second_data[$i]$3} )
    {
        $i++;
    }
    print "$_\n";
}

Not the answer you're looking for? Browse other questions tagged or ask your own question.