david yeah
david yeah

Reputation: 254

Get a variable in a variable in shell

I search for someone who can help me on a problem :

I have a file.txt which contains information like that :

2014-05-30 15:34:46,170 [18] INFO  - Login - TimeTaken 00:00:00.1866202
2014-05-30 15:34:46,170 [18] INFO  - Subscribe - TimeTaken 00:00:00.1866202
2014-05-30 15:34:46,170 [18] INFO  - Subscribe - TimeTaken 00:00:00.1866202
2014-05-30 15:34:46,170 [18] INFO  - GetInfos - TimeTaken 00:00:00.1866202
2014-05-30 15:34:46,170 [18] INFO  - Subscribe - TimeTaken 00:00:00.1866202
2014-05-30 15:34:46,170 [18] INFO  - Login - TimeTaken 00:00:00.1866202
2014-05-30 15:34:46,170 [18] INFO  - Login - TimeTaken 00:00:00.1866202

And the associate script :

records=$(grep 'TimeTaken' file.txt)

timems=$(echo "$records" | cut -d " " -f 10 | cut -c 8-)

echo $timems

averageTime=$(echo "$records" | awk '{
    print $timems
    arr[$6]+=$timems
    count[$6]++
}
END {
 for (key in arr) printf("%s\,%s\,%s\n", count[key], key, arr[key] / count[key])
}'    | sort +0n -1)

echo "$averageTime"

When I launch this script, here is the result :

0.1866202 0.1866202 0.1866202 0.1866202 0.1866202 0.1866202 0.1866202
awk: cmd. line:7: warning: escape sequence `\,' treated as plain `,'
1,GetInfos,2014
3,Login,2014
3,Subscribe,2014
2014-05-30 15:34:46,170 [18] INFO  - GetInfos - TimeTaken 00:00:00.1866202
2014-05-30 15:34:46,170 [18] INFO  - Login - TimeTaken 00:00:00.1866202
2014-05-30 15:34:46,170 [18] INFO  - Login - TimeTaken 00:00:00.1866202
2014-05-30 15:34:46,170 [18] INFO  - Login - TimeTaken 00:00:00.1866202
2014-05-30 15:34:46,170 [18] INFO  - Subscribe - TimeTaken 00:00:00.1866202
2014-05-30 15:34:46,170 [18] INFO  - Subscribe - TimeTaken 00:00:00.1866202
2014-05-30 15:34:46,170 [18] INFO  - Subscribe - TimeTaken 00:00:00.1866202

For the last field of 1,GetInfos,2014 (ie : 2014), I want to have the average of timeTaken group by my methods. I don't understand why when I make "echo $timems" I have the good value outside of "averageTime" variable bu not the good one inside.

Hope someone can help me on that.

Thanks a lot!

Upvotes: 2

Views: 40

Answers (1)

miindlek
miindlek

Reputation: 3563

In your script $timems stores a list of values. This is why you can't just calculate with this variable in awk.

Perhaps the following code fits your needs.

averageTime=$(grep 'TimeTaken' file.txt | awk -F'[ :]' '{
    arr[$9]+=$14
    count[$9]++
}
END {
 for (key in arr) printf("%s,%s,%.7f\n", count[key], key, arr[key] / count[key])
}' | sort +0n -1)

echo "$averageTime"

Upvotes: 1

Related Questions