Saturday, May 31, 2014

Count the number of lines and words in a file

Script

#!/usr/bin/perl

open(INFILE,$ARGV[0]);

$line_count = 0;
$word_count = 0;

while ($line = <INFILE>)
{

$line_count++;
@words_on_this_line = split(" ",$line);
$word_count += scalar(@words_on_this_line);
}

print "The file $ARGV[0] contains ",$line_count," lines and ",
$word_count, " words\n";


Execution

./file-details /etc/resolv.conf
The file /etc/resolv.conf contains 5 lines and 12 words



./file-details /etc/inittab
The file /etc/inittab contains 26 lines and 149 words


No comments:

Post a Comment