On Fri, Jun 01, 2001 at 04:17:06PM -0500, Nichole Bialczyk wrote:
> so how do i delete the lines that i read in? (keeping the first one so
> that the file still exists)
>
> On Fri, Jun 01, 2001 at 02:08:25PM -0700, Paul wrote:
> >
> > --- Nichole Bialczyk <[EMAIL PROTECTED]> wrote:
> > > to be more specific, i want to do this: read and delete all of the
> > > lines from a log file, except for the first one.
> >
> > open IN, $file or die "$file:$!";
> > <IN>; # throw away first line;
> > print <IN>; # print the rest of the file.
You can't really 'delete' lines from a file with Perl (see discussion of
this in the FAQ: perldoc -q 'change one line'). You need to create new
file contents (which in your case is just the first line of the old file)
and write these contents out to the file you want.
The best solution for what you want to do depends on whether you need
to do any processing to the lines you plan to throw away. If you do,
then I'd probably do something like:
my $new_file;
open IN, $file or die "$file: $!\n";
while (<IN>) {
if ($. == 1) {
$new_file = $_
} else {
# your processing goes here
}
}
close IN;
open OUTFILE, ">$file" or die "Can't open $file for writing: $!\n";
print OUTFILE $new_file;
If all you want to do is truncate the file to the first line, I'm sure
there's all sorts of clever ways to do it. In lieu of that, I offer this
one liner, which works but is probably fraught with obvious (except to
me) bugs:
perl -pi.bak -e 'exit unless $. ==1;' filename
The only thing really obscure about any of this is finding what line
you're on in the file, which is where the $. variable comes in right
handy. (See perldoc perlvar for way more info on this and the various
ways using it can bite you when you're least expecting it.)
Cheers,
Bill
--
Bill Stilwell
[EMAIL PROTECTED]
It's all margins.
Oh, just read my weblog: http://www.marginalia.org