bash-3.00$ ./test.pl
4
bash-3.00$ cat -n UnprocessedData.out
1 a
2 b
3 c
4 d
5
6
7
8
9
10
bash-3.00$ cat test.pl
#!/usr/bin/perl -w
$ARGV[0]||='/home/user01/UnprocessedData.out';
$linenum=0;
open OR,$ARGV[0];
while (<OR>) {
next if /^\s*$/;
$linenum++;
}
print "$linenum\n";
close OR;
$: cat -n test
1 a
2 b
3 c
4 d
5
6
7
8 e
9 f
10
11
12 g
13
14 h
$: perl -e 'while(<>){next if /^\s*$/;$count+=1;} print "$count\n"' test
8
---------- Post updated at 03:04 PM ---------- Previous update was at 02:43 PM ----------
Are you running this script in windows machine ?
---------- Post updated at 03:17 PM ---------- Previous update was at 03:04 PM ----------
$ARGV[0]||='/home/user01/UnprocessedData.out'; --> check any file is passed as argument, if not then take the file /home/user01/UnprocessedData.out $linenum=0; --> initalize the value to 0 open OR,$ARGV[0]; --> FileHandler OR to open the file while (<OR>) { --> loop the file upto the last line next if /^\s*$/; --> skip the next line code if the line is blank $linenum++; --> once if condition fails, it will increase the variable value (it means, it is not blank line) } --> end of while loop print "$linenum\n"; -->print the linenum variable value. close OR; --> close the fileHandler
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 ...
more at man perlfaq5
and a wrapper for that:
NAME
File::CountLines - efficiently count the number of line breaks in a
file.
Since different operating systems have different ideas of what a
newline is, you can specifiy a "style" option ...
more at perldoc File/CountLines