#!/bin/sh -u # simple shell script using an AWK script to sum a given column of numbers # # $0 fieldno [filenames...] # # fieldno: the field number to sum in the input file(s) # # Sum a column of integers. (May contain dollar signs.) # 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 # Assign fieldno and then shift it away, leaving only file names (if any). # We will pass the file names to AWK, below. # XXX This script fragment is missing input validation! # fieldno=$1 shift # 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 a selector in front of it to select only lines # where the given field contains only digits or dollar signs. # # Variables are passed into the AWK script using special syntax # 'fieldno=$fieldno' immediately following the script string, below: # awk ' BEGIN { sum=0; count=0 } # Look for digits and dollar signs only. # $fieldno ~ /^[$0-9]+$/ { num = $fieldno print "DEBUG num before gsub is", num gsub("[$]","",num) print "DEBUG num after gsub is", num # make sure after gsub that there are digits left! if ( num ~ /^[0-9]+$/ ) { sum = sum + num count = count + 1 } else { print $fieldno, "is non numeric in", $0 next } } END { print "sum of", count, "numbers is", sum } ' fieldno=$fieldno "$@"