We help IT Professionals succeed at work.
Get Started

How to delete the last two lines of a Text file, keeping all empty lines in the body of the file?

carcase asked
Last Modified: 2008-02-01
***I'm very new to PERL.

How does one delete the last two lines of a file while keeping all other lines (even when it contains only escape sequences \r\n )?

My original file contains several groupings, each delimited by \r\n\r\n.  Within each grouping are subsections, each delimited by \r\n.

group 1 line 1
group 1 line2

group 2 line 1
group 2 line 2

When I have attempted to remove the last two lines by reading the original file into an array, then writing out to a new file, the \r\n\r\n  sequences  are replaced with a single \r\n.  This merges all my groupings into one

group 1 line 1
group 1 line 2
group 2 line 1
group 2 line 2
My code is attached.
open (FIL, "BillTestFile.txt");
@array=<FIL>; #read the file into an array
$end=@array; #total in array
close (FIL);
$end=$end-2; #total in array minus two
#reopen file for writing
open (FIL, ">OUTPUT.txt") or die "Can't open file: $!\n"; 
for($i = 0; $i < $end; $i++){
     print FIL "$array[$i]"; #write array at line "i"
     $i++; #go to next line
} #End for loop
close (FIL);

Open in new window

Watch Question
This problem has been solved!
Unlock 1 Answer and 7 Comments.
See Answer
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE