Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

copy part of file and paste it into another file 1

Status
Not open for further replies.

liondari

Technical User
Oct 4, 2004
7
GR
Hello everybody,

I was not able to solve this problem:
I have a file polygon.dat with this structure:

#some text
.
#some text
MASK POLYGON
23
1.0750465E+03
1.1066547E+03
.
.
1.2288103E+03
EXIT
#some text
.
#some text

I would like to copy the column of numbers between the lines
"MASK POLYGON" and "EXIT" and insert it into another file after some specific line which starts also with "MASK POLYGON".

Thanks
 
Code:
open (INFILE, "polygon.dat");
open (OUTFILE, "otherpolygon.dat");

# Copy the lines into array @copy
my $startCopying = 0;
my @copy = ();
while (<INFILE>) {
   chomp $_; # removes \n chars from end of lines

   if ($_ eq 'MASK POLYGON') {
      $startCopying = 1;
   }
   elsif ($_ eq 'END POLYGON') {
      $startCopying = 0;
   }

   push (@copy, $_) if $startCopying;
}

# Loop through the new file. Insert our
# old array of lines where necessary.
my @newFile = ();
while (<OUTFILE>) {
   chomp $_;

   push (@newFile,$_); # save all lines to @newFile

   if ($_ eq 'MASK POLYGON') {
      # we paste the text from polygon.dat after this line
      push (@newFile,@copy);
   }
}

# now @newFile should be the contents of the
# other file, with the text copied from the
# first file in the right place.
close (INFILE);
close (OUTFILE);

# now we open the out file for writing
open (OUTFILE, ">newpolygon.dat");
print OUTFILE join ("\n",@newFile);
close (OUTFILE);
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top