Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot
 
PerlMonks  

Count number of lines in a text file

by Scott7477 (Chaplain)
on Mar 23, 2006 at 18:52 UTC ( #538824=snippet: print w/ replies, xml ) Need Help??

Description: Short and simple...I borrowed the counting code from ActiveState's Perl docs and added some to make this accessible from the command line.
#Count number of lines in a file
$filename = <@ARGV>;
 $lines = 0;
    open(FILE, $filename) or die "Can't open `$filename': $!";
    while (sysread FILE, $buffer, 4096) {
        $lines += ($buffer =~ tr/\n//);
    }
    close FILE;
print "The number of lines in $filename is $lines.\n";

Comment on Count number of lines in a text file
Download Code
Re: Count number of lines in a text file
by davidrw (Prior) on Mar 23, 2006 at 19:10 UTC
    different approach using Tie::File (should also work w/large files):
    perl -MTie::File -MFcntl=O_RDONLY -le 'tie @array, "Tie::File", shift, + mode => O_RDONLY or die $!; print scalar @array' /etc/hosts
    .. and of course there's wc on *nix or from ppt
Re: Count number of lines in a text file
by aweeraman (Novice) on Mar 23, 2006 at 20:04 UTC
    Here's another variation that gets rid of a few lines:
    open (FILE, $ARGV[0]) or die "Can't open '$ARGV[0]': $!"; $lines++ while (<FILE>); close FILE; print "$lines\n";
      don't need $lines -- $. does it for you (see perlvar)
      perl -le 'open FILE, "/etc/passwd"; @_=<FILE>; print $.'
      And (similar to QM's golf reply:
      perl -lne 'END{print $.}' /etc/passwd
Re: Count number of lines in a text file
by QM (Vicar) on Mar 23, 2006 at 20:31 UTC
    What about this oft-quoted golf shot?
    perl -pe '}{$_=$.' filename

    -QM
    --
    Quantum Mechanics: The dreams stuff is made of

      Very tricky. So because of the }, the continue { print $_; } block is no longer attached to the loop, but to the {$_=$.} bare block. I never knew this trick with -p. (I knew about -ne '...}{...' but not what it did with -p.)
        Yes. But -p and -n only differ by the continue/print. Compare -p:
        > perl -MO=Deparse -pe"#stuff#" LINE: while (defined($_ = <ARGV>)) { (); } continue { print $_; }
        to -n:
        > perl -MO=Deparse -ne"#stuff#" LINE: while (defined($_ = <ARGV>)) { (); }

        -QM
        --
        Quantum Mechanics: The dreams stuff is made of

Re: Count number of lines in a text file
by ambrus (Abbot) on Mar 24, 2006 at 10:36 UTC

    Here's yet another golf variation, provided there's only one filename and that's a real filename (not a glob or something you can give to the two-arg open):

    exec wc,-ll,pop
Re: Count number of lines in a text file
by gube (Parson) on Mar 28, 2006 at 07:24 UTC

    Hi try this,

    #! /usr/bin/perl use strict; open(IN, "test.txt"); my @str = <IN>; close(IN); print scalar(@str);
      Excuse my French, but why the **censored** would you store the whole file in memory just to count the lines? Why hardcode the filename in the script? Why bother to open and close the file, when <> is so handy?

      Sorry, please forgive the tirade, I don't know what came over me. It must be the ghost of Abigail-II...Certainly TIMTOWTDI. (I find many of my cow-orkers skip over the "gather requirements" phase of programming, and jump headfirst into the shallow end of the implementation pool.)

      While playing with this, I wanted to check how similar schemes work. For instance, don't do this either:

      perl -e 'print scalar(()=<>),"\n"' filename
      I tried this on a 300MB file, which took a long time (I waited several minutes before killing it), lots of memory, and started swapping to disk.

      I tried the following on the same 300MB file, which took about 10 seconds, and never went above 2MB memory:

      perl -pe "}{$_=$." filename
      Inside a script, you could do this:
      #!/your/perl/here -p }{$_=$.
      (yes, that compiles and runs too) though you may prefer the more conventional
      #!/your/perl/here use strict; use warnings; while (<>) {} print "$.\n";
      If you want to get fancy, and feed it more than one file at a time, keeping track of each file, try this:
      #!/your/perl/here use strict; use warnings; my $file_count = @ARGV; while (<>) {} continue { if (eof) { # print file names for multiple files print "$ARGV: " if ($file_count > 1); print "$.\n"; close ARGV; } }
      Someone will ask me for command line arguments to leave off the filenames, and provide summary statistics for multiple files. I'll leave that to OMAR. (Wow, there really is an OMAR! But he doesn't write much :(

      -QM
      --
      Quantum Mechanics: The dreams stuff is made of

Re: Count number of lines in a text file
by ajbryant59 (Initiate) on Sep 12, 2007 at 21:25 UTC
    Here's a one-liner inspired by some of the other solutions: $num_lines = scalar(() = ${${new IO::File "<filename"}});
      Sorry to have to submit a retraction but the one-liner I submitted before doesn't work. I was sure I had this one working but c'est la vie. Sorry to clutter the postings.
      what about my($NumLines)=scalar <$Filename>
        That only works if the current line just happens to contain a number which equals the number of lines. <> in scalar context just reads a single line.

        But this works:

        perl -wE'say~~(()=<>)' yourfile
Re: Count number of lines in a text file
by Anonymous Monk on Jan 23, 2013 at 08:53 UTC
    Everybody should be aware that in an ASCII file, the last line may NOT contain a '\n' character. This means the following code:
    while (sysread FILE, $buffer, 4096) { $lines += ($buffer =~ tr/\n//); }
    will never count the last line! Please do not use the above code !!!

    Use:

    while (<FILE>) { $lines++ }

Back to Snippets Section

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: snippet [id://538824]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others chilling in the Monastery: (4)
As of 2014-07-25 05:14 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My favorite superfluous repetitious redundant duplicative phrase is:









    Results (167 votes), past polls