计算unix中日志文件中两个时间段之间的行数

时间:2016-02-15 12:26:22

标签: unix

Log file:

<l:event dateTime="2014-02-12 08:05:37.950"..........
<l:event dateTime="2014-02-12 08:08:77.980"..........
.
.
.
<l:event dateTime="2014-02-12 10:25:39.550"..........

我想计算08:00到10:30之间的数字线,如何获得它。 ? 注意:日志文件可能有也可能没有准确时间为08:00或10:30的条目

1 个答案:

答案 0 :(得分:0)

你可以使用perl(不是任何一个perl guru,所以可能比必要的更复杂)

perl -n -e 'BEGIN {$cnt=0} END { print $cnt."\n"} /dateTime="\d{4}-\d{2}-\d{2} (\d{2}:\d{2}:\d{2})/ && $1 ge "08:00:00" && $1 lt "10:00:00" && $cnt++' < log.txt

......或为了便于阅读;

perl -n                  -- runs the script for each line in the input file

BEGIN { $cnt=0 }         -- start by setting $cnt to 0
END { print $cnt."\n"}   -- when all is done, print $cnt
/dateTime="\d{4}-\d{2}-\d{2} (\d{2}:\d{2}:\d{2})/
                         -- match for time format, keeping the time in the group
$1 ge "08:00:00"         -- check if the time is greater or equal to 08:00:00
$1 lt "10:30:00"         -- check if time is less than 10:30:00 
$cnt++                   -- if all matches are ok, increase cnt

来自评论的编辑;

/dateTime="\d{4}-\d{2}-\d{2} (\d{2}:\d{2}:\d{2})/

...基本上是一个正则表达式,它匹配您给出的日期时间字段格式的行(4位+ - + 2位+ - + ...)并提取时间part(括号部分)到$1以与限制进行比较。它应该在一天内的任何时间段内工作,所以10:25-10:35应该可以正常工作。