计算unix日志文件中两个时间段之间的行数 [英] Count number of lines between two time period in log file in 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 的条目
I want to count the number lines between 08:00 to 10:30, how to get it. ? Note: Log file may or may not have the entry with exact time of 08:00 or 10:30
推荐答案
你可以使用 perl(无论如何都不是 perl 大师,所以可能比必要的更复杂)
You could use perl (not a perl guru by any stretch, so may be more complex than necessary)
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 位数字 + -
+ ...) 并将时间部分(括号中的部分)提取到 $1
中以与限制进行比较.它应该适用于一天内的任何时间跨度,因此 10:25-10:35 应该可以正常工作.
...basically is a regex that matches the rows with the datetime field format you're giving (4 digits + -
+ 2 digits + -
+ ...) and extracts the time part (the parenthesized part) into $1
for comparison with the limits. It should work for any time span within a single day, so 10:25-10:35 should work just fine.
这篇关于计算unix日志文件中两个时间段之间的行数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!