《懒人Shell脚本》之四——日志条数动态实时统计

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

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)时间戳转化为时间

[root@laoyang zq_testing]# tcurtime=date -d @$scurtime "+%F %T"

[root@laoyang zq_testing]# echo $tcurtime

2016-08-11 11:15:06


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;

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

一行指令完成统计

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

上一篇:FastDFS安装教程,详细步骤,适合新手学习(一)


下一篇:flowable 6.6.0 去掉自带的登录权限