awk/sed を使用してパターンをファイルの行に置き換える [重複]

awk/sed を使用してパターンをファイルの行に置き換える [重複]

first.html次のコードを含むファイルがあります。

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

second.txtこれで、次の値を含む別のファイルがあります。

hahaha
hehehe

「headerValue」のすべての値を2番目のファイルの値に置き換えたいと思います。

例えば。交換first.html

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

second.txt ファイルのデータは first.txt ファイルのデータとは何の関係もありません。

ベストアンサー1

これが可能な答えの1つです。しかし、私はPerlを使用します。 2番目のファイルは空行をチェックしません。そして代替品はハードコーディングされています。

#!/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";
}

おすすめ記事