Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses


by Anonymous Monk
on Nov 09, 2000 at 23:57 UTC ( #40798=perlquestion: print w/replies, xml ) Need Help??
Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

how to count the tota number of empty lines in a textfile?

Replies are listed 'Best First'.
Re: perl
by Fastolfe (Vicar) on Nov 10, 2000 at 00:45 UTC
    A one-liner that will do this:
    perl -ne '$count++ unless /\S/; print "$count\n" if eof' <filename
      A slightly shorter version perl -pe '$c++ unless /\S/}{$_=$c' Cheers,
Re: perl
by kilinrax (Deacon) on Nov 10, 2000 at 00:01 UTC
    Assuming by 'empty' you mean 'containing only space characters':
    open FILE, "file.txt"; my $count; while (<FILE>) { $count++ unless /\S+/; } close FILE; print $count;
      Just as a footnote, if you do not want to count lines that contain a tab or some other such whitespace, you can substitue /\S+/ with /^$/ in either this code or in Fastolife's below
      This is the best solution I would use, though /\S/ is sufficient.
Heresy = Re: perl
by arturo (Vicar) on Nov 10, 2000 at 01:57 UTC

    Or, on *NIX systems,

    shell prompt>grep -c '^[:blank:]*$'

    -c tells grep to merely count lines which match the pattern (0 or more blanks between the beginning and end of the line)

    Philosophy can be made out of anything. Or less -- Jerry A. Fodor

RE: perl
by extremely (Priest) on Nov 10, 2000 at 05:18 UTC
    On most modern systems this may suffice as well.
    grep -vc '[^[:space:]]' filenames...

    Of course it isn't perl but it is sexy =) Tho to be honest I really use a space and ^Vtab rather than that crappy ansi notation =).

    Someone needs to snag the most recent regexp engine from perl and make a real greperl or grep with a -P flag to use that engine. Too many good tweaks in the perl regexp are going unexercised. =)

    $you = new YOU;
    honk() if $you->love(perl)

        There is all kinds of hard in the world:
        root# ls -l `which perl`
        -rwxr-xr-x    3 root     root       733687 Apr 15  2000 /usr/bin/perl
        root# ls -l `which grep`
        -rwxr-xr-x    1 root     root        75600 Feb  3  2000 /bin/grep

        One of them is footprint. I love perl, but it's a big stick to hit grep with. =)

        $you = new YOU;
        honk() if $you->love(perl)

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://40798]
Approved by root
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others perusing the Monastery: (9)
As of 2017-02-23 21:35 GMT
Find Nodes?
    Voting Booth?
    Before electricity was invented, what was the Electric Eel called?

    Results (351 votes). Check out past polls.