dr jerry
dr jerry

Reputation: 10026

Perl: How do I remove the first line of a file without reading and copying whole file

I do have a whole bunch of files in a directory and from every file I want to remove the first line (including carriage return). I can read the whole file into an array of strings and write all but the first element to a new file, but that looks a bit cumbersome to me are there better ways? Oh the prefered language is Perl.

Upvotes: 15

Views: 19075

Answers (6)

daxim
daxim

Reputation: 39158

use Tie::File qw();
for my $filename (glob 'some_where/some_files*') {
    tie my @file, 'Tie::File', $filename or die "Could not open $filename: $!";
    shift @file;
}

Upvotes: 5

user3458
user3458

Reputation:

How about

tail +2

in shell?

(edit: in newer Linux you may need tail -n +2 (thank you, GNU! :( ))

Upvotes: 11

Zaid
Zaid

Reputation: 37136

As pointed out by Schwern, the following does not perform an early exit as I had originally thought it would:

perl -pi -e '$_ = q// and last if $. == 1;' myFile

Seems like one cannot avoid processing the whole file after all.

Upvotes: -1

leonbloy
leonbloy

Reputation: 75896

perl -n -i -e 'print unless $. == 1' myfile

This is similar to stocherilac's answer.

But, in any case (and in all the others answer given!) you are always reading the full file. No way of avoiding that, AFAIK.

Upvotes: 9

pilcrow
pilcrow

Reputation: 58524

Oh the prefered language is Perl.

Sometimes sed is a better sed than even perl:

sed -i 1d *

Upvotes: 9

Kavet Kerek
Kavet Kerek

Reputation: 1315

Try this one liner

perl -pi -e '$_ = "" if ( $. == 1 );' filename

I've used it before, should be all you need.

Upvotes: 24

Related Questions