Re: Print all lines in a file except the last two
by diotalevi (Canon) on May 20, 2004 at 14:06 UTC
|
Yes - a small queue would do this. Since you're so new, you'll do yourself a world of good by picking up a copy of the inexpensive book Learning Perl (also known as the Llama book) from O'Reilly.
while (<>)
{
push @queue, $_;
print shift @queue if @queue > 2;
}
| [reply] [Watch: Dir/Any] [d/l] |
Re: Print all lines in a file except the last two
by neniro (Priest) on May 20, 2004 at 15:10 UTC
|
#!/usr/bin/perl
use strict;
use warnings;
use Tie::File;
my $file = "file.txt";
my @lines;
tie @lines, 'Tie::File', $file or die $!;
print $_,"\n" for (@lines[0 .. $#lines-2]);
untie @lines;
| [reply] [Watch: Dir/Any] [d/l] |
Re: Print all lines in a file except the last two
by mifflin (Curate) on May 20, 2004 at 14:36 UTC
|
$lines = `/usr/bin/wc -l afile.txt`;
open(F, '<afile.txt') || die 'cannot open afile.txt';
$cntr = 0;
while (<F>) {
$cntr++;
print;
last if $cntr == $lines - 2;
}
on my unix box.
| [reply] [Watch: Dir/Any] [d/l] |
|
$. < $lines - 2 and print while <F>
| [reply] [Watch: Dir/Any] [d/l] |
Re: Print all lines in a file except the last two
by mifflin (Curate) on May 20, 2004 at 14:49 UTC
|
another idea...
If you don't want the last two lines you could truncate them
open(F, '+<afile.txt') || die 'cannot open afile.txt';
while (<F>) {
push(@addrs, tell(F)) unless eof(F);
}
truncate(F, $addrs[-2]) || die 'cannot truncate afile.txt';
This will remove the last two lines in a file.
I got the idea for this in the Perl Cookbook. Recipe 8.10
If you don't have that book I recommend it. | [reply] [Watch: Dir/Any] [d/l] |
Re: Print all lines in a file except the last two
by Ryszard (Priest) on May 20, 2004 at 14:56 UTC
|
Assuming a CR after each line:
1 2 3 4
1234567890123456789012345678901234567890123456789
perl -e 'open(F,'f');@f=<F>;pop@f;pop@f;print"$_"foreach@f'
| [reply] [Watch: Dir/Any] [d/l] |
|
| [reply] [Watch: Dir/Any] [d/l] [select] |
|
Why a counter and imply it's short when you have a foreach, and a print"$_" ?
print for@f[0..-2] is shorter.
Edit: Wow, I really do live in a little fluffy bunny world where everyone's happy, there's no war, pizza isn't fattening, Darth Vader was never an annoying child, the Six million Dollar Man really was a good tv show, new shoes are comfy, my girlfriend's bum never looks big in this, and code like this works.
Kind of surprised I didn't lose all the xp I'd ever gotten on this one. hardburn posted the correct code below.
| [reply] [Watch: Dir/Any] [d/l] [select] |