天天看點

懶人Shell腳本》之四——日志條數動态實時統計

1、需求點

1)輸入:日志實時更新:目前日志表以秒級更新日志,每秒有多條日志更新。格式如下:

2016-08-11 11:02:09
2016-08-11 11:02:09
2016-08-11 11:02:09
2016-08-11 11:02:09
2016-08-11 11:02:10
2016-08-11 11:02:10
2016-08-11 11:02:10
2016-08-11 11:02:10
2016-08-11 11:02:10
2016-08-11 11:02:10
2016-08-11 11:02:10
2016-08-11 11:02:10
2016-08-11 11:02:11
2016-08-11 11:02:11
2016-08-11 11:02:11           

2)實時輸出:每個時刻值對應的2016-08-11 11:06:56 47

2016-08-11 11:06:57 18 
2016-08-11 11:06:58 44 
2016-08-11 11:06:59 22 
2016-08-11 11:07:00 42 
2016-08-11 11:07:01 44 
2016-08-11 11:07:02 12 
2016-08-11 11:07:03 37 
2016-08-11 11:07:04 18 
2016-08-11 11:07:05 18 
2016-08-11 11:07:06 38 
2016-08-11 11:07:07 48 
2016-08-11 11:07:08 38 
2016-08-11 11:07:09 21 
2016-08-11 11:07:10 31 
2016-08-11 11:07:11 18 
2016-08-11 11:07:12 20 
2016-08-11 11:07:13 3 
2016-08-11 11:07:14 43           

要求:一行腳本完成統計。

2、腳本實作原理

1)循環産生時間值,并寫入檔案。

時刻值的産生需要注意時間和時間戳的#時間形式列印

[root@laoyang zq_testing]# tcurtime=

date "+%F %T"

[root@laoyang zq_testing]# echo $tcurtime

2016-08-11 11:15:06

2)時間轉化為時間戳

[root@laoyang zq_testing]# scurtime=

date -d "$tcurtime" +%s

[root@laoyang zq_testing]# echo $scurtime

1470885306

3)時間戳轉化為時間

date -d @$scurtime "+%F %T"

4)循環環讀取檔案,使用awk的詞頻統計功能完成頻率統計。

3、腳本實作

#構造時間腳本
[root@laoyang zq_testing]# cat build_time.sh
#!/bin/sh
#generate random values
function random()
{
  min=$1;
  max=$2
  randomval=$((RANDOM%$max+$min))
  echo $randomval
}

#generate time values
function build_conn_time()
{
  rm -rf ./output.log
  touch ./output.log
  cat /dev/null > ./output.log

  tflag=0
  nextsecond=0
  while :
  do
  if [[ $tflag -eq 0 ]];then
  tcurtime=`date "+%F %T"`
  echo "xtcurtime="$tcurtime
  tflag=1
  else
  #時間戳轉化為時間
  tcurtime=`date -d @$nextsecond "+%F %T"`
  echo "next tcurtime="$tcurtime
  fi

  #時間格式化 為時間戳
  scurtime=`date -d "$tcurtime" +%s`

  #産生2-50之間的随機數
  cyccnt=$(random 2 50);
  if [[ -z $cyccnt ]]; then
  cyccnt=10
  fi
  echo "cyccnt="$cyccnt
  i=0
  while (( $i<$cyccnt))
  do
  echo $tcurtime >> output.log
  i=$(($i+1))
  done

  #更新下一秒 ,時間戳可以求和操作
  nextsecond=$(($scurtime+1))
  sleep 1
  done
}

build_conn_time;           

一行指令完成統計

root@laoyang zq_testing]# while : ; do cat output.log | sort | awk '{ count[$0]++ }\
END { printf("%-14s %s\n","curtime","Count");\
for(ind in count)\
{ printf("%-14s %d\n",ind,count[ind]); } }' | sort ; sleep 1 ; done           

作者:銘毅天下

轉載請标明出處,原文位址:

http://blog.csdn.net/laoyang360/article/details/52188384

繼續閱讀