开发者

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 m开发者_如何学JAVAe are there better ways? Oh the prefered language is Perl.


Try this one liner

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

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


How about

tail +2

in shell?

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


Oh the prefered language is Perl.

Sometimes sed is a better sed than even perl:

sed -i 1d *


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.


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;
}


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜