![日志文件中周期之间的持续时间](https://linux22.com/image/1483064/%E6%97%A5%E5%BF%97%E6%96%87%E4%BB%B6%E4%B8%AD%E5%91%A8%E6%9C%9F%E4%B9%8B%E9%97%B4%E7%9A%84%E6%8C%81%E7%BB%AD%E6%97%B6%E9%97%B4.png)
如果这太基础了,我很抱歉,但我有一个包含此类信息的日志:
Mai 5 12:34:00 xoengine XO[1287]: [Xo|xoengineMain.cpp:122|0xb88ec60] starting xoengine 4.0.1.2 (x86) from [/usr/bin/xoengine]
Mai 5 12:35:00 xoengine XO[1287]: [Xo|DataStorage.cpp:1370|0xb88ec60] loading database [/var/xoengine/xoengine.db]
Mai 5 12:35:10 xoengine XO[1287]: [Xo|DataStorage.cpp:2043|0xb88ec60] database loaded in 40ms
Mai 5 12:37:00 xoengine XO[1287]: [Xo|xoengineMain.cpp:318|0xb88ec60] xoengine is running
Mai 7 10:32:00 xoengine XO[1287]: [Xo|xoengineMain.cpp:122|0xb88ec60] starting xoengine 4.0.1.2 (x86) from [/usr/bin/xoengine]
Mai 7 10:32:58 xoengine XO[1287]: [Xo|xoengineMain.cpp:152|0xb88ec60] demo licensed for 5 machines expiring on 2017-10-04
Mai 7 10:33:00 xoengine XO[1287]: [Xo|xoengineMain.cpp:318|0xb88ec60] xoengine is running
我的目的是得到这样的结果:
Cycle: 1 Duration: 00:03:00
Cycle: 2 Duration: 00:01:00
...
时间是根据在行中找到单词“starting”和“running”来计算的,因此计算出“starting”和“running”之间所花费的时间。谢谢
答案1
我测试了我编写的这段代码,并且它可以工作:
#!/bin/bash
logfile="/var/log/file.log"
countStart=0
countStop=0
getDuration()
{
read -r h m s <<< $(echo $1 | tr ':' ' ' )
echo $(((h*60*60)+(m*60)+s))
}
while read line; do
if [[ $line =~ 'starting xoengine' ]]; then
starting=`echo $line | awk '{print $3}'`
START=$(getDuration $starting)
let countStart+=1
elif [[ $line =~ 'xoengine is running' ]]; then
stopping=`echo $line | awk '{print $3}'`
STOP=$(getDuration $stopping)
let countStop+=1
fi
if [ $countStart -eq $countStop ] && [ $countStop -ne 0 ]; then
DIFF=$((STOP-START))
echo "Cycle $countStart Duration: $((DIFF/60))m $((DIFF%60))s"
fi
done < $logfile