simple script to tally the numbers in a defined column of text
Sample input file..
row1 1 2 3 4 5 6 7 8 9
row2 2 3 4 5 6 7 8 9 10
row3 1 2 3 4 5 6 7 8 9
row4 1 2 3 4 5 6 7 8 9
row5 1 2 3 4 5 6 7 8 9
row6 1 2 3 4 5 6 7 8 9
row7 1 2 3 4 5 6 7 8 9
row8 1 2 3 4 5 6 7 8 9
row9 1 2 3 4 5 6 7 8 9
row10 1 2 3 4 5 6 7 8 9
Sample outputs
./column-tally.sh -f input -c second -v ON
input is readable
Column is second
row1 1 1
row2 2 3
row3 1 4
row4 1 5
row5 1 6
row6 1 7
row7 1 8
row8 1 9
row9 1 10
row10 1 11
The cumulative value of the second column is 11
./column-tally.sh -f input -c tenth -v ON
input is readable
Column is tenth
row1 9 9
row2 10 19
row3 9 28
row4 9 37
row5 9 46
row6 9 55
row7 9 64
row8 9 73
row9 9 82
row10 9 91
The cumulative value of the tenth column is 91
#!/bin/bash
usage()
{
cat << EOF
usage: $0 -f input.txt -c first second
$0 -f input.txt -c first second -v ON
This script will tally the numerical values in the specified column.
OPTIONS:
-f input file
-c column number {first,second....tenth)etc..
-v verbosity {ON}
EOF
}
if [ $# -lt 4 ]
then
usage
exit 1
fi
while getopts ":f:c:v:" opt; do
case $opt in
f)
InPutFile=$OPTARG
if [ -r "$InPutFile" ]
then
echo "$InPutFile is readable"
else
echo "Unable to read input file --> $InPutFile !!!"
usage
exit 1
fi
;;
v)
Verbose=$OPTARG
;;
c)
echo "Column is $OPTARG"
Column=$OPTARG
if [[ $Column == "first" || $Column == 'second' || $Column == 'third' || $Column == 'fourth' || $Column == 'fifth' || $Column == 'sixth' || $Column == 'seventh' || $Column == 'eighth' || $Column == 'ninth' || $Column == 'tenth' ]]
then
true
else
echo" not a valid column value"
echo" must be either: first second third fourth fifth sixth seventh eighth ninth tenth"
usage
exit 1
fi
;;
:)
echo "Option -$OPTARG requires an argument." >&2
usage
exit 1
;;
?)
echo "Invalid option: -$OPTARG" >&2
usage
exit 1
;;
* )
echo "Unimplemented option: -$OPTARG" >&2
usage
exit 1
;;
esac
done
cumulative=0
while read -r first second third fourth fifth sixth seventh eighth ninth tenth; do
let " cumulative += Column "
let " value = Column "
if [[ $Verbose == 'ON' || $Verbose == 'OFF' ]]
then
true
else
echo "invalid Verbosity setting please use -v ON or -v OFF"
exit 1
fi
if [ $Verbose == 'ON' ]
then
echo -e "$first \t$value \t$cumulative"
else
true
fi
done < $InPutFile
echo "The cumulative value of the $Column column is $cumulative"