in reply to Read n lines from the top of a text file

The number of the last line read from the last filehandle read is stored in $., so you can do something like this to show the first 10 lines of a file:
perl -e "while(<>){print qq'$.: $_'; last if $.==10}" yourfile.txt

Update: ++ danger for a wealth of alternatives, as well as the more practical one-liner!

--
I'd like to be able to assign to an luser

Replies are listed 'Best First'.
Re: Re: I feel stupid.
by danger (Priest) on Dec 23, 2001 at 11:09 UTC

    Well, ++Albannach for not reading the whole file. But you could have saved some typing if we just want to print the first 10 lines:

    perl -pe '$.>10&&last' yourfile.txt

    However, the original poster might appreciate a little more verbosity and variation (and we'll get the lines into an array instead of just printing them):

    # the Albannach method expanded (only read $n_lines from file): #!/usr/bin/perl -w use strict; my $n_lines = 10; my $file = 'blah'; my @lines; open(FILE, $file)|| die "Can't $!"; while(<FILE>){ push @lines, $_; last if $. == $n_lines; } close FILE; print @lines; __END__ # A slight variation (only reads $n_lines): #!/usr/bin/perl -w use strict; my $n_lines = 10; my $file = 'blah'; my @lines; open(FILE, $file)|| die "Can't $!"; for (1 .. $n_lines) { push @lines, scalar <FILE>; } close FILE; print @lines; __END__ # let's read $n_lines one character at a time: #!/usr/bin/perl -w use strict; my $n_lines = 10; my $file = 'blah'; $_ = ''; open(FILE, $file)|| die "Can't $!"; $_ .= getc(FILE) while tr/\n// < $n_lines; close FILE; my @lines = split/^/m; print @lines; __END__ # aww heck, lets read it all but only keep $n_lines: #!/usr/bin/perl -w use strict; my $n_lines = 10; my $file = 'blah'; my @lines; open(FILE, $file)|| die "Can't $!"; @lines[0..$n_lines-1] = <FILE>; close FILE; print @lines; __END__ # same idea, different implementation: #!/usr/bin/perl -w use strict; my $n_lines = 10; my $file = 'blah'; open(FILE, $file)|| die "Can't $!"; my @lines = (<FILE>)[0..$n_lines-1]; close FILE; print @lines; __END__ # stand on someone else's shoulders (or head as the case may be): #!/usr/bin/perl -w use strict; my $n_lines = 10; my $file = 'blah'; my @lines = `head -n$n_lines $file`; print @lines; __END__

    so I was bored!