LoginSignup
0
0

More than 3 years have passed since last update.

【Linux】awkでログに含まれる数値を集計及び平均する方法

Posted at

ログから数値を抽出し、集計します。

以下のログファイルのspendtimeを集計します。

test.log
2019/08/06 22:31:00.300 KEY0 spendtime:5ms
2019/08/06 22:31:01.300 KEY1 spendtime:6ms
2019/08/06 22:31:02.300 KEY2 spendtime:7ms
2019/08/06 22:31:03.300 KEY0 spendtime:1ms
2019/08/06 22:31:04.300 KEY1 spendtime:2ms
2019/08/06 22:31:05.300 KEY2 spendtime:3ms
2019/08/06 22:31:06.300 KEY0 spendtime:100ms
2019/08/06 22:31:07.300 KEY1 spendtime:23ms
2019/08/06 22:31:07.300 KEY2 spendtime:12ms

まずは、数値を抽出する必要があります。
awk -f '[ :]でセパレータを指定しています。

test.log
[test@localhost ~]$ cat test.log | awk -F'[ :]' '{print $7}'
5ms
6ms
7ms
1ms
2ms
3ms
100ms
23ms
12ms

msをカットします。

test.log
[test@localhost ~]$ cat test.log | awk -F'[ :]' '{print substr($7,1,length($7)-2)}'
5
6
7
1
2
3
100
23
12

変数sumで集計し、最後にsumをプリントします。

test.log
[test@localhost ~]$ cat test.log | awk -F'[ :]' '{sum+=substr($7,1,length($7)-2)} END {print sum}'
159

平均はNRでsumを割ります。

test.log
[test@localhost ~]$ cat test.log | awk -F'[ :]' '{sum+=substr($7,1,length($7)-2)} END {print sum/NR}'
17.6667
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0