开发者

perl + append text between two lines in file

I need to edit file , the main issue is to append text between two known lines in the file

for example I need to append the following text

   a b c d e f 

   1 2 3 4 5 6

   bla bla

Between the first_line and the second_line

 first开发者_开发知识库_line=")"

 second_line="NIC Hr_Nic ("

How to do this by perl ?

lidia


Assuming you have a minimal knowledge of Perl, you can use the solution to this question to read the whole file (assuming it's not too big) in an array, and then you can simply add the new line as an element in the correct position (and rewrite it back to the filesystem).

If you don't know how to write a file back, here it comes:

open FH, ">>$file_name" or die "can't open '$file_name': $!"; # <<<< outside the loop
foreach ( @your_array )
{

    print FH $_;

}
close FH; # <<<<<<<< outside the loop


You can make the insertion in a temporary file :

use strict;
use warnings;

open my $in, '<', 'file_in' or die "can't open 'file_in' for reading : $!";
open my $out, '>', 'file_out' or die "can't open 'file_out' for writing : $!";
my $previous = '';
while(my $line=<$in>) {
    chomp($line);
    if($previous eq ')' && $line eq 'NIC Hr_Nic (') {
        print $out "$previous\na b c d e f\n1 2 3 4 5 6\nbla bla\n";
    } elsif($previous ne '') {
        print $out $previous,"\n";
    }
    $previous = $line;
}
print $out $previous;
close $in;
close $out;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜