Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse score reports and extract point sums and averages

Tags:

linux

bash

i want to calculate:

  • the total points (sum)
  • the today points (sum)
  • the total points (average)
  • the today points (average)

i have no idea with bash scripting other than i need to start with: #!/bin/bash

here's a sample of my file

#file 14516 - 2011-01-26 19:01:00 EDT#
user: [email protected] / id(11451611)
lastlogin: 1295896515
total_points: 11.76 / today: 5.21
gameid: 51

user: [email protected] / id(11837327)
lastlogin: 1293893041
total_points: 416.1 / today: 98.1
gameid: 49

user: [email protected] / id(11451611)
lastlogin: 1294917135
total_points: 1.76 / today: 0.21
gameid: 51
like image 867
Rob Avatar asked Jan 27 '12 01:01

Rob


1 Answers

You can use this:

#!/bin/bash

if [ ! -f $1 ]; then
  echo "File $1 not found"
  exit 1
fi

number=$(grep total_points $1 | wc -l )
sumTotal=$(grep total_points $1 | awk '{sum+=$2} END { print sum }')
sumToday=$(grep total_points $1 | awk '{sum+=$5} END { print sum }')

echo "Total SUM: $sumTotal"
echo -n "Total AVG: "
echo "scale=5;$sumTotal/$number" | bc

echo "Today SUM: $sumToday"
echo -n "Today AVG: "
echo "scale=5;$sumToday/$number" | bc

Then save to a file like: script.sh

Change the permission to executable: chmod +x script.sh

Then run it: ./script.sh sample.txt

This will output:

Total Record: 3
Total SUM: 429.62
Total AVG: 143.20666
Today SUM: 103.52
Today AVG: 34.50666

Note: $1 will the the input file.

Here's more help about the bc command, grep, awk

like image 63
Book Of Zeus Avatar answered Oct 02 '22 16:10

Book Of Zeus