LDP/LDP/guide/docbook/abs-guide/col-totaler2.sh

51 lines
1.0 KiB
Bash
Raw Normal View History

2001-07-10 14:25:50 +00:00
#!/bin/bash
2004-01-05 13:20:57 +00:00
# Another version of the "column totaler" script
#+ that adds up a specified column (of numbers) in the target file.
2005-05-08 20:09:31 +00:00
# This one uses indirect references.
2001-07-10 14:25:50 +00:00
ARGS=2
2008-11-23 22:43:47 +00:00
E_WRONGARGS=85
2001-07-10 14:25:50 +00:00
2008-11-23 22:43:47 +00:00
if [ $# -ne "$ARGS" ] # Check for proper number of command-line args.
2001-07-10 14:25:50 +00:00
then
echo "Usage: `basename $0` filename column-number"
2001-09-04 13:27:31 +00:00
exit $E_WRONGARGS
2001-07-10 14:25:50 +00:00
fi
2008-11-23 22:43:47 +00:00
filename=$1 # Name of file to operate on.
column_number=$2 # Which column to total up.
2001-07-10 14:25:50 +00:00
#===== Same as original script, up to this point =====#
2008-11-23 22:43:47 +00:00
# A multi-line awk script is invoked by
# awk "
# ...
# ...
# ...
# "
2001-07-10 14:25:50 +00:00
# Begin awk script.
2009-09-29 15:08:03 +00:00
# -------------------------------------------------
2001-07-10 14:25:50 +00:00
awk "
2008-11-23 22:43:47 +00:00
{ total += \$${column_number} # Indirect reference
2001-07-10 14:25:50 +00:00
}
END {
print total
}
" "$filename"
2009-09-29 15:08:03 +00:00
# Note that awk doesn't need an eval preceding \$$.
# -------------------------------------------------
2001-07-10 14:25:50 +00:00
# End awk script.
2004-01-05 13:20:57 +00:00
# Indirect variable reference avoids the hassles
2005-05-08 20:09:31 +00:00
#+ of referencing a shell variable within the embedded awk script.
2004-01-05 13:20:57 +00:00
# Thanks, Stephane Chazelas.
2001-07-10 14:25:50 +00:00
2008-11-23 22:43:47 +00:00
exit $?