| 1 | #!/bin/bash |
| 2 | |
| 3 | # Adds up a specified column (of numbers) in the target file. |
| 4 | # Floating-point (decimal) numbers okay, because awk can handle them. |
| 5 | |
| 6 | ARGS=2 |
| 7 | E_WRONGARGS=85 |
| 8 | |
| 9 | if [ $# -ne "$ARGS" ] # Check for proper number of command-line args. |
| 10 | then |
| 11 | echo "Usage: `basename $0` filename column-number" |
| 12 | exit $E_WRONGARGS |
| 13 | fi |
| 14 | |
| 15 | filename=$1 |
| 16 | column_number=$2 |
| 17 | |
| 18 | # Passing shell variables to the awk part of the script is a bit tricky. |
| 19 | # One method is to strong-quote the Bash-script variable |
| 20 | #+ within the awk script. |
| 21 | # $'$BASH_SCRIPT_VAR' |
| 22 | # ^ ^ |
| 23 | # This is done in the embedded awk script below. |
| 24 | # See the awk documentation for more details. |
| 25 | |
| 26 | # A multi-line awk script is here invoked by |
| 27 | # awk ' |
| 28 | # ... |
| 29 | # ... |
| 30 | # ... |
| 31 | # ' |
| 32 | |
| 33 | |
| 34 | # Begin awk script. |
| 35 | # ----------------------------- |
| 36 | awk ' |
| 37 | |
| 38 | { total += $'"${column_number}"' |
| 39 | } |
| 40 | END { |
| 41 | print total |
| 42 | } |
| 43 | |
| 44 | ' "$filename" |
| 45 | # ----------------------------- |
| 46 | # End awk script. |
| 47 | |
| 48 | |
| 49 | # It may not be safe to pass shell variables to an embedded awk script, |
| 50 | #+ so Stephane Chazelas proposes the following alternative: |
| 51 | # --------------------------------------- |
| 52 | # awk -v column_number="$column_number" ' |
| 53 | # { total += $column_number |
| 54 | # } |
| 55 | # END { |
| 56 | # print total |
| 57 | # }' "$filename" |
| 58 | # --------------------------------------- |
| 59 | |
| 60 | |
| 61 | exit 0 |