icon Top 9 categories map      RocketAware > Perl >

How do I count the number of lines in a file?

Tips: Browse or Search all pages for efficient awareness of Perl functions, operators, and FAQs.



Home

Search Perl pages


Subjects

By activity
Professions, Sciences, Humanities, Business, ...

User Interface
Text-based, GUI, Audio, Video, Keyboards, Mouse, Images,...

Text Strings
Conversions, tests, processing, manipulation,...

Math
Integer, Floating point, Matrix, Statistics, Boolean, ...

Processing
Algorithms, Memory, Process control, Debugging, ...

Stored Data
Data storage, Integrity, Encryption, Compression, ...

Communications
Networks, protocols, Interprocess, Remote, Client Server, ...

Hard World
Timing, Calendar and Clock, Audio, Video, Printer, Controls...

File System
Management, Filtering, File & Directory access, Viewers, ...

    

How do I count the number of lines in a file?

One fairly efficient way is to count newlines in the file. The following program uses a feature of tr///, as documented in the perlop manpage. If your text file doesn't end with a newline, then it's not really a proper text file, so this may report one fewer line than you expect.

    $lines = 0;
    open(FILE, $filename) or die "Can't open `$filename': $!";
    while (sysread FILE, $buffer, 4096) {
        $lines += ($buffer =~ tr/\n//);
    }
    close FILE;


Source: Perl FAQ: Files and Formats
Copyright: Copyright (c) 1997 Tom Christiansen and Nathan Torkington.
Next: How do I make a temporary file name?

Previous: How do I change one line in a file/delete a line in a file/insert a line in the middle of a file/append to the beginning of a file?



(Corrections, notes, and links courtesy of RocketAware.com)


[Overview Topics]

Up to: File filtering and processing




Rapid-Links: Search | About | Comments | Submit Path: RocketAware > Perl > perlfaq5/How_do_I_count_the_number_of_lin.htm
RocketAware.com is a service of Mib Software
Copyright 2000, Forrest J. Cavalier III. All Rights Reserved.
We welcome submissions and comments