Link to home
Start Free TrialLog in
Avatar of paulwhelan
paulwhelan

asked on

delete last 2 lines

anyone know the perl to open a file
and delete the last two lines?
thanks
paul
Avatar of prakashk021799
prakashk021799

One way is to open the file, read everything but the last two lines, write them in a temp file and copy the temp file over to the original.

Another way is suggested by
perldoc -q 'delete a line'

.....

In the unique case of deleting lines at the end of a file, you
can use tell() and truncate().  The following code snippet deletes the last line of a file without making a copy or reading the whole file into memory:

        open (FH, "+< $file");
        while ( <FH> ) { $addr = tell(FH) unless eof(FH) }
        truncate(FH, $addr);

Error checking is left as an exercise for the reader.




The above is an example of deleting the last line in a file. You will need to change this code to delete last two lines.
Avatar of paulwhelan

ASKER

that doesnt seem to delte a line for me
paul
What does it delete then? part of the line? more than a line? nothing at all?

More details please.
nothing at all...
i changed it to

open (FH, "+< ../htdocs/deletefile.html");
while ( <FH> ) { $addr = tell(FH) unless eof(FH) }
                             truncate(FH, $addr);


would that be the problem?
paul
I tested the code with a test file containing 10 lines. After I ran the code, I saw only 9 lines in the file. Works for me.

Did you check the return value of open?
Did you remember to close the file, just in case, after truncate?
the three lines i posted are all i had in my file
do i need more
ie
close (FH);
ASKER CERTIFIED SOLUTION
Avatar of prakashk021799
prakashk021799

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
close is not really mandatory, althought it is preferred to have it there for clean closing.

What about checking the return value of open?
So, what was the problem in your code?
i didnt have the line
$addr = tell(FH);
in the loop
thanks!
paul