Tuesday, 16 October 2012

Practical no-8: Write a awk script that uses all its Features


Practical no-8: Write a awk script that uses all its Features

As an example of using numeric expressions, look at the following script that counts the number of blank
lines in a file:

#!/bin/sh
for i in $@ ;
do
    if [ -f $i ] ; then
        echo $i
        awk ' /^ *$/ { x=x+1 ; print x ; }' $i
    else
        echo "ERROR: $i not a file." >&2
    fi
done

In the awk command, you increment the variable x and print it each time a blank line is encountered.
Because a new instance of the awk command runs for each file, the count is unique of each file.
Consider the file urls.txt, which contains four blank lines:
$ cat urls.txt
http://www.cusa.berkeley.edu/~ranga

http://www.cisco.com

ftp://prep.ai.mit.edu/pub/gnu/
ftp://ftp.redhat.com/

http://www.yahoo.com/index.html
ranga@kanchi:/home/ranga/pub

ranga@soda:/home/ranga/docs/book/ch01.doc

For urls.txt, the output of this script looks like the following:
urls.txt
1
2
3
4

No comments:

Post a Comment