How to insert lines, 2 lines after the corresponding line in Perl

advertisements

I am trying to insert one of the data file or some characters in to existing file in perl.

For example, lets say we have 'data' file and 'extraData' file. If data file contains the height information, insert info that is in extraData file right after one line after the Height.

Data:

red fox
likes to run
Height:
120
speed:
140

Extra Data:

Weight:
70

Result:

red fox
likes to run
Height:
120
Weight:
70
speed:
140

Currently I have implemented the code below and the weight information is printing right after the "height" has been found. I would like to print the height and its information and then append the weight information.

Assume $weight has the weight info from extraData file:

use File::Copy;
copy( "data", "copy" ) or die "Copy failed: $!";
unlink("data.txt");

open FILE, '<', 'copy';
open OUT,  '>', 'data';

while ( my $line = <FILE> ) {
    if ( grep {/Height/} $line ) {
        print OUT $line;
        print OUT "Weight \n";
        print OUT $weight;
    }
    else {
        print OUT $line;
    }
}

Result:

red fox
likes to run
Height:
Weight:
70
120
speed:
140

Any Help would be appreciated, Thanks


perl -plne 'print "Weight:\n\n70\n" if(/speed/);' test.txt

should do it