tags:

views:

15

answers:

2

hi all

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

A: 

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
p.marino
+1  A: 

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;
M42