Hi Sheela,
On Tuesday 23 Mar 2010 15:06:24 sheela b wrote:
> Hi All,
>
> How to delete last 10 lines of a file using Perl one liner?
>
> I used the following one liner to delete first 10 lines of a file,
>
> perl -i.bak -ne 'print unless 1..10' test.txt
>
If it doesn't have to be a one-liner, you can do it efficiently using the
following script:
<<<
#!/usr/bin/perl
use strict;
use warnings;
use File::ReadBackwards;
use Getopt::Long;
my $count;
GetOptions(
"n=i" => \$count,
);
if (!defined($count))
{
die "Please specify -n for the line count.";
}
my $filename = shift;
my $bw = File::ReadBackwards->new($filename)
or die "Could not backwards-open '$filename' - $!";
foreach my $idx (1 .. $count)
{
$bw->readline();
}
my $wanted_len = $bw->tell();
$bw->close();
open my $truncate_fh, "+<", $filename
or die "Could not truncate-open '$filename' - $!";
truncate($truncate_fh, $wanted_len);
close($truncate_fh);
>>>
If you still insist on it being a one-liner, see:
http://mail.perl.org.il/pipermail/perl/2005-August/007316.html
You can do it as a one liner in a much less elegant way by using a cyclical
queue, but I can't be bothered to implement it.
Regards,
Shlomi Fish
>
> Regards
> Sheela
--
-----------------------------------------------------------------
Shlomi Fish http://www.shlomifish.org/
Parody on "The Fountainhead" - http://shlom.in/towtf
Deletionists delete Wikipedia articles that they consider lame.
Chuck Norris deletes deletionists whom he considers lame.
Please reply to list if it's a mailing list post - http://shlom.in/reply .
--
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]
http://learn.perl.org/