| 1 | #!/bin/bash |
| 2 | |
| 3 | # Yet another version of the "column totaler" script (col-totaler.sh) |
| 4 | #+ that adds up a specified column (of numbers) in the target file. |
| 5 | # This uses the environment to pass a script variable to 'awk' . . . |
| 6 | #+ and places the awk script in a variable. |
| 7 | |
| 8 | |
| 9 | ARGS=2 |
| 10 | E_WRONGARGS=85 |
| 11 | |
| 12 | if [ $# -ne "$ARGS" ] # Check for proper number of command-line args. |
| 13 | then |
| 14 | echo "Usage: `basename $0` filename column-number" |
| 15 | exit $E_WRONGARGS |
| 16 | fi |
| 17 | |
| 18 | filename=$1 |
| 19 | column_number=$2 |
| 20 | |
| 21 | #===== Same as original script, up to this point =====# |
| 22 | |
| 23 | export column_number |
| 24 | # Export column number to environment, so it's available for retrieval. |
| 25 | |
| 26 | |
| 27 | # ----------------------------------------------- |
| 28 | awkscript='{ total += $ENVIRON["column_number"] } |
| 29 | END { print total }' |
| 30 | # Yes, a variable can hold an awk script. |
| 31 | # ----------------------------------------------- |
| 32 | |
| 33 | # Now, run the awk script. |
| 34 | awk "$awkscript" "$filename" |
| 35 | |
| 36 | # Thanks, Stephane Chazelas. |
| 37 | |
| 38 | exit 0 |