
我創建了一個腳本,用於查看特定數量的毫秒/秒的日誌檔案和 grep。我創建了一些可以查看最小值和最大值的東西,但是我需要找到清單的平均值。
logdir_8080='/opt/product/apachetomcat/8.5.5_8080/logs'
cd "$logdir_8080"
get_file=`ls -rt localhost_access_log.*.txt|tail -1`
cat $get_file | tail -1000 | grep "objectId" | awk -F 'HTTP/1.1" 200' '{
print $2}'|awk -F' ' '{ print $2 }' | sort - n>/opt/product/apachetomcat/apm/epagent/epaplugins/centrica/correspondence_log_files/8080.txt
最小值:
cat /opt/product/apachetomcat/apm/epagent/epaplugins/centrica/correspondence_log_files/8080.txt|head -1
最大值:
cat /opt/product/apachetomcat/apm/epagent/epaplugins/centrica/correspondence_log_files/8080.txt|tail -1
清單的想法:
233
249
283
283
302
303
332
333
643
851
965
965
972
1022
1135
1182
1213
1232
1264
1273
1390
1403
1414
1429
1474
1537
1540
1543
1545
1556
1565
1566
1577
1589
1591
1599
1602
1621
1622
1647
1653
1705
1740
1772
1774
1933
1935
1983
1990
如何得到平均值?
答案1
如果文件中只有數字,則可以使用單一 awk 指令來取得所有內容。
awk 'BEGIN {themin=10000000; themax=0; thecount=0; thesum=0}
{for (i=1; i<=NF; i++) {
thesum += $i;
thecount++;
if ($i < themin) {themin = $i}
if ($i > themax) {themax = $i}
}}
END {
printf("The min is %d\nThe max is %d\nThe sum is %d\nThe total number of items is %d\nThe average of those items is %d\n", themin, themax, thesum, thecount, int(thesum/thecount))
}' _file_
我把它分解了,這樣你就可以看到不同的部分。
BEGIN 只是初始化所有要使用的變數。變數 themin 可以設定為您想要的任何大值,只要它大於檔案中的任何值即可。
中間部分只是循環遍歷每一行以及該行中的每個欄位。它對數字進行求和,並對所有數字進行計數,以便最後可以進行簡單的除法。兩個 if 語句收集最小值和最大值。
END 列印所有相關訊息,包括最小值、最大值和平均值。
希望這可以幫助。
答案2
無需為已經有出色解決方案的問題編寫自己的解決方案。畢竟,您是在 SuperUser 而不是 StackOverflow 上詢問的。
例如使用GNUdatamash
$ datamash min 1 max 1 mean 1 < yourFile
233 1990 1272.0408163265
或使用包中的工具num-utils
$ numbound -l yourFile
233
$ numbound yourFile
1990
$ numaverage yourFile
1272.04081632653