Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert a line into the middle of an existing file

Tags:

perl

consider an example where i want to insert few lines of text when particular patter matches(if $line=~m/few lines in here/ then insert lines in next line):

*current file:*

"This is my file and i wanna insert few lines in here  and other
text of the file will continue."

*After insertion:*

"This is my file and i wanna insert few lines in here  this is my
new text which i wanted to insert and other text of the file will
continue."

This is my code:

my $sourcename = $ARGV[1];
my $destname = $ARGV[0];
print $sourcename,"\n";
print $destname,"\n";
my $source_excel = new Spreadsheet::ParseExcel;  
my $source_book = $source_excel->Parse($sourcename) or die "Could not open source Excel file $sourcename: $!";

my $source_cell;
#Sheet 1 - source sheet page having testnumber and worksheet number
my $source_sheet = $source_book->{Worksheet}[0];            #It is used to access worksheet

$source_cell = $source_sheet->{Cells}[1][0];                #Reads content of the cell;
my $seleniumHost = $source_cell->Value; 
print $seleniumHost,"\n";

open (F, '+>>',"$destname") or die "Couldn't open `$destname': $!";
my $line;

while ($line = <F>){
print $line;
if($line=~m/FTP/){
#next if /FTP/;
print $line;
print F $seleniumHost;}
like image 943
Sirga Avatar asked Nov 30 '11 05:11

Sirga


2 Answers

The perlfaq covers this. How do I change, delete, or insert a line in a file, or append to the beginning of a file?

Files are fixed blocks of data. They behave much like a piece of paper. How do you insert a line into the middle of a piece of paper? You can't, not unless you left space. You must recopy the whole thing, inserting your line into the new copy.

like image 163
Schwern Avatar answered Oct 02 '22 00:10

Schwern


In a perl one-liner :

perl -ane 's/few lines in here  and other\n/this is my\nnew text which i wanted to insert and other /; s/continue./\ncontinue./; print ' FILE

If you don't want a one-liner, it's easy to takes the substitutions in any script ;)

like image 44
Gilles Quenot Avatar answered Oct 02 '22 01:10

Gilles Quenot