Monday, January 23, 2012

Couting the number of blank lines in a file

Counting the number of blank lines in a file.

Here are a few ways to count the number of blank lines in a file using shell scripting.

Assume we have a file named test which has the following contents :



Note that the above file has 10 blank lines includin the one at the end. Let see how we can count the same using commands or scripts

1. Using grep :



When -c option is used with grep, it counts the number of occurrences of the search string and outputs the same. 2. Using awk:



Awk reads one line of the file at a time, hence we compare each line with the blank line i.e. ^$ and increment a count whenever there is match and print the final count before exiting.

3. Using shell scripting :



Save the script as line_count.sh . Give it execute permission using

chmod 777 line_count.sh

And then execute it



The above script uses a while loop to pass through the file, one line at a time and on reading each line an "if" statement is used to comapre the line with the blank line. Note the use of double [ with the if statement. A single [ will not be able to interpret the regular expressions in an if statement. When the comparision is a success a count is incremented and the same is printed at the end.

0 comments:

Post a Comment