從日誌檔案計算每小時數據

從日誌檔案計算每小時數據

我想從日誌檔案中獲取每小時的記錄數。這是範例資料;

001:2017-05-23 00:00:01 002:10.10.10.63
001:2017-05-23 00:00:03 002:10.10.10.63
001:2017-05-23 00:00:05 002:10.10.10.63
001:2017-05-23 00:00:07 002:10.10.10.63
001:2017-05-23 00:00:09 002:10.10.10.63
001:2017-05-23 01:00:12 002:10.10.10.63
001:2017-05-23 01:00:14 002:10.10.10.63

從上面的數據輸出應該是;

00 = 5
01 = 2

答案1

cut -f2 -d' ' logfile
| cut -f1 -d:
| sort
| uniq -c
| sed 's/ *\([0-9]\+\) \([0-9][0-9]\)/\2 = \1/'
| sort
  1. 只輸出時間。
  2. 只提取小時數。
  3. 對輸出進行排序 - 以下行需要
  4. 計算每小時發生的次數,輸出count hour
  5. 修復格式
  6. 按小時排序

答案2

您可以使用find以下-printf屬性,我在日常操作中使用了它:

find /path/ -type f -printf '%TY-%Tm-%Td-%TH\n' | sort | uniq -c

答案3

解決方案有很多,其中之一是

log_file=/var/log/messages                        # log file for extract
d=2022-10-28                                      # start date
while [ "$d" != 2022-11-04 ]; do                  # loop for date range
  echo $d                                         # echo ACTUAL date
  for h in {00..24}; do                           # loop for hours
    act=$(date -d "$d" +'%b %d')" $h:"            # create date for ACTUAL date in requested format: %b return month in Jan Feb..., %d return month number
    echo $act                                     # Print actual hour
    grep "^$act" $log_file                        # grep $ACT from beginning of line of log_file and count lines
  done
  d=$(date -I -d "$d + 1 day")                    # add +1 day for start date to the main loop
done 

相關內容