简体   繁体   中英

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

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

应该做

I recommend you read: perlfaq5 - How do I change, delete, or insert a line in a file, or append to the beginning of a file?

In this case I would recommend using $INPLACE_EDIT for modifying the file, and the flip-flop operator to determine when to insert your new data:

use strict;
use warnings;

my $file = 'data';

local @ARGV = $file;
local $^I   = '.bak';
while (<>) {
    print;
    print "Weight:\n70\n" if /Height/ .. /\d/ and /\d/;
}
# unlink "$file$^I"; # Optional delete backup

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM