realKSMC
realKSMC

Reputation: 115

Search output for time and summarize it

The final goal is to setup an website with dynamic statistics. For that I already created an mysql database and count the total amount of known players on our minecraft server. Next step is to show the playtime of all players altogether.

I have an "activetime.conf" where the playtime for all players is listed.

activetime.conf:

config {
    auto-save=300
    default-range=5
    max-range=10
}
players {
    "111-111-1111-11-11" {
        name=playerjack
        time="2h13m25s"
    }
    222-2-22222-2-222 {
        name=playergert
        time="14m13s"
    }
}

What I already have:

players=$(ls -l /path | grep -v ^d | grep -v ^t | wc -l)
mysql -u root -pmypass mydatabase -e "UPDATE mytable SET players = '$players';"
hours_played=$(grep -E '"*h*m*s"' /path/activetime.conf)
echo $hours_played

We have the following string "hours_played" and like to search it for time information + summarize the times to finally show the full hours only.

hours_played:

time="2h13m25s" time="14m13s"

Final result should be:

2

Why the result is 2 ?

2h13m25s + 14m13s = 2h27m38s (=2h)

Upvotes: 1

Views: 49

Answers (1)

l'L'l
l'L'l

Reputation: 47169

One thing you could do is use a function to parse the time info (hours, mins, seconds):

#!/bin/bash

active_time() {

    regex='time.*\"(.+)h(.+)m(.+)s\"'

    while read -r str; do
    if [[ $str =~ $regex ]] ; then
        h=$(( h + BASH_REMATCH[1] ))
        m=$(( m + BASH_REMATCH[2] ))
        s=$(( s + BASH_REMATCH[3] ))
    fi
    sub=$(( m / 60  ))
    tot=$(( h + sub ))
    done<"/path/active_time.conf"
    echo "${tot} total hours"
}

So instead of echoing the last last line echo $hours_played you would just call:

active_time

Calling the function totals up the hours and minutes, so for example:

time="8h13m25s"
time="6h54m13s"

Would output:

15 total hours

*Summing the seconds and adding to the total has been omitted as an exercise for the OP to add if desired.

Upvotes: 2

Related Questions