#!/bin/sh -u # full shell script using an AWK script to sum a given column of numbers # # $0 [-q] [-v] [colnum] [files...] # # colnum: the column number to sum in the input file(s) # -q: quiet - only the sum, nothing else # -v: verbose - print matching records # # Sum a column of floating-point numbers and print some stats. # Sum stdin if no files given. # # NOTE: This script fragment is incomplete - it does not follow all # the script guidelines set out in "script_style.txt". It also # contains many "Instructor-Style" comments that you must not use in # your own scripts. See script_style.txt for details. # # -IAN! idallen@idallen.ca # Handle the command-line colnum and option arguments. # Break the loop when the first non-option argument (filename) is found. # col=1 quiet=0 verbose=0 while [ $# -gt 0 ]; do case "$1" in [1-9] | [1-9][0-9] ) col=$1 ; shift ;; -q) quiet=1 ; shift ;; -v) verbose=1 ; shift ;; *) break ;; esac done # The AWK program is passed as one large multi-line single-quoted string. # The program contains only three "lines" - a BEGIN, a middle, and and END. # The middle line has no selector in front of it; it is executed for # every line in the input. # # Variables are passed into the AWK script using special syntax # 'col=$col' immediately following the script string, below: # exec awk ' BEGIN { xmin = 1e99; sum = 0; xmax = -1e99; linecount=0; sumcount=0; } { ++linecount num = $col gsub("[,;()$=~!@#%^&*_]","",num) if ( num ~ /^[-+]?[0-9.][0-9.]*$/ ) { if ( num < xmin ) { xmin = num; minrec = $0; } if ( num > xmax ) { xmax = num; maxrec = $0; } sum += num ++sumcount } } END { if ( linecount != sumcount ) { print "*** Warning: lines:", linecount, "lines summed:", sumcount } if ( sumcount == 0 ) exit 1 if ( quiet ) { print sum } else { if ( verbose ) { print minrec print maxrec } print "total", sum, "count", sumcount, "min", xmin, "max", xmax, "average", sum/sumcount } } ' col=$col quiet=$quiet verbose=$verbose ${1+"$@"}