We help IT Professionals succeed at work.

deleting last line in file if not blank

NorthReptile
NorthReptile asked
on
I am logging to an XML file which continually appends and I want to remove the last root tag so that the XML validates when I open it in a web browser, for example.

I am trying to delete the last entry in a log file and found this code snippet which achieved that

    open (FH, "+< $logFile")               or die "can't update $file: $!";
    while ( <FH> ) {
        $addr = tell(FH) unless eof(FH);
    }
    truncate(FH, $addr)                 or die "can't truncate $file: $!";


However, if there are blank lines it only removes the blank line. I want to remove any lines up and including the last </log> tag

I'd prefer a clean perl script but bash would be fine too
Comment
Watch Question

How big is the file?  When you say "continually appends", how often does the file get written to and is there only one process writing to the file?

For a general case, I would use Tie::File.
use Tie::File;
my @lines;
tie @lines, 'Tie::File', $filename or die "could not tie $filename: $!";
while ($lines[-1] =~ m{\A\s*\z|$end_tag_regex}) {
    pop @lines;
}
# add new stuff here
untie @lines;

Open in new window

Author

Commented:
it's a monthly log file so probably a few hundred megabytes. The same program that writes to it will remove the last line so no issue there.

I will give this a go. Would this solution be efficient in performance and file reading/writing?
Tie::File is very efficient (compared to other methods) for manipulating large files as it does not read the whole file into memory (I'm not sure exactly how it accomplishes this but it works).  I've never noticed any issues with performance using Tie::File.

Author

Commented:
Thanks that worked really well!