DOC HOME SITE MAP MAN PAGES GNU INFO SEARCH PRINT BOOK
 
Automating frequent tasks

Expanding the example: counting words

At present, our readability analyzer program does very little processing. It can trap signals (preventing it from terminating if interrupted), it can scan the command line for arguments, and it sets up some useful routines for printing help and clearing the screen. However, we now want the program to perform a useful task.

Given the size of the skeleton structure we have already created, it might look as if it will take a lot of work to make it do anything useful. However, surprisingly little additional programming is needed.

As a first step towards writing a style analysis program, it would be useful to know how many words, characters and lines there are in the target file. We can use wc to obtain this information for any given file; we can also use backquotes to capture the output and process it.

To add word counting to our program, all we need to do is change the following lines:

   23 :	
   24 :	do_something()
   25 :	{
   26 :	  wordcount=`wc -w ${fname} | awk '{ print $1 }'`
   27 :	  lines=`wc -l ${fname} | awk '{ print $1 }'`
   28 :	  chars=`wc -c ${fname} | awk '{ print $1 }'`
   29 :	  echo "File ${fname} contains:
   30 :	        ${wordcount}\t\twords
   31 :	        ${lines}\t\tlines
   32 :	        ${chars}\t\tcharacters "
   33 :	}
The main task of the program is to call the function do_something. This function runs wc, pipes the output through a short awk command, and traps the result in a variable; then it prints a formatted report.

For example:

   $ rap -f rap
   

File rap contains: 243 words 95 lines 1768 characters

$

The awk program '{ print $1 }' prints the first field on every line awk reads from the standard input. This is a typical awk program: short, integrated into a shell script, and used to carry out a transformation on a stream of text. For more information on using awk, see ``Using awk''.

The important point to note here is that by encapsulating the functionality of the program in a subroutine (the function do_something) we have made it a lot easier to change the program. (Ideally do_something would be written as three separate functions, to count words, lines, and characters. However, because it is comparatively short it is presented here as a single unit.)

We can make our program do something else entirely, simply by modifying do_something and changing the help text in _help. Most of the program is actually a skeleton that we can use to hang useful subroutines off: you can reuse it as a starting point for your own batch mode shell scripts.


Next topic: Making menus
Previous topic: Generating a simple menu: the select statement

© 2003 Caldera International, Inc. All rights reserved.
SCO OpenServer Release 5.0.7 -- 11 February 2003