У меня есть файл журнала, который выглядит следующим образом:
[info] Estimate the time: 2.7s
[info] Estimate some other time: 7.9s
[info] Estimate the time: 5.6s
[debug] variable x uninitialized
Я хотел бы рассчитать среднее время после "Оценить время:", в данном случае (2,7 + 5,6) /2=4,15
Как быстро получить этот номер с помощью команд Linux или Python? Спасибо.
Всего 3 ответа
Вот скрипт Python, использующий регулярное выражение:
import re
# Open the file and get the data in a string
f = open('your_log', 'r')
text = f.read()
# Use regex to find the pattern
matches = re.findall(r'Estimate the time: (d+.d+)s', text)
if matches:
times = [float(time) for time in matches] # Convert str in float
mean = sum(times) / len(times) # Calculate the mean with built-in methods
print(mean)
else:
print("no data")
sum=0
cnt=0
for log in logs:
if "Estimate the time" in log:
sum += extractSecondFromLog()
cnt += 1
print(sum/cnt)
awk '/[info] Estimate the time:/ { map[cnt++]=+$5 } END { for (i in map) { cnt1++;tot=tot+map[i] } print tot/cnt1 }' logfile
Пояснение:
awk '/[info] Estimate the time:/ { # Process lines that contain "[info] Estimate the time:"
map[cnt++]=+$5 # Create an array called map with an incrementing index and the 5th space delimited field as the value
}
END { # Process at the end of the file
for (i in map) {
cnt1++; # Loop through the array and increment a counter with each iteration
tot=tot+map[i] # Create a running total variable
}
print tot/cnt1 # Print the running total divided by the count.
}' logfile