2013-10-31 61 views
0

我分析套接字服务器的大量的日志文件来跟踪一些事件日志文件,一个给定的时间比较筛选的最近2个数量级。我在使用shell脚本获取给定时间内的最近2条消息日志(一个在之前,另一个在给定时间之后)方面存在问题。在这种情况下,我唯一可以使用的事情是日志文件的日期时间值与来自壳牌脚本(.ksh)

e.g. triggering time: 2013-10-31 07:29:45.311 
    think I have an event from another log at 2013-10-31 07:29:45.311 and need to filter 
the most recent message log one is before above time and other one is after from below sample log. 

    given time = 2013-10-31 07:29:45.311 
    then triggered times for most recent log messages should be 
    1) before the given time: message at 2013-10-31 07:29:34.415 
    2) after the given time: message at 2013-10-31 07:30:34.473 

可以使用shell脚本吗?

Sample log: 

    2013-10-31 07:23:33.931 INFO - TTT153|Receive|0000131|.... 
    2013-10-31 07:24:35.273 INFO - TTT153|Receive|0000131|.... 
    2013-10-31 07:25:33.973 INFO - TTT153|Receive|0000131|.... 
    2013-10-31 07:26:34.111 INFO - TTT153|Receive|0000131|.... 
    2013-10-31 07:27:34.151 INFO - TTT153|Receive|0000131|.... 
    2013-10-31 07:28:34.273 INFO - TTT153|Receive|0000131|.... 
    2013-10-31 07:29:34.415 INFO - TTT153|Receive|0000131|.... 
    2013-10-31 07:30:34.473 INFO - TTT153|Receive|0000131|.... 
    2013-10-31 07:31:34.595 INFO - TTT153|Receive|0000131|.... 
    2013-10-31 07:32:34.616 INFO - TTT153|Receive|0000131|.... 
    2013-10-31 07:33:35.673 INFO - TTT153|Receive|0000131|.... 
+0

有人下来投了这个问题,请解释原因。 – Jotne

回答

1

它的一些复杂的事情,但可以通过转换日期到纪元时间完成。

value="2013-10-31 07:29:45.311" 
awk ' 
    { 
    split($1,a,"-") 
    split($2,b,"[:.]") 
    t1=mktime(a[1] " " a[2] " " a[3] " " b[1] " " b[2] " " b[3]) "." b[4] 
    split(v,c,"[- :.]") 
    t2=mktime(c[1] " " c[2] " " c[3] " " c[4] " " c[5] " " c[6]) "." c[7] 
    } 
    t1>t2 {print l "\n" $0;exit} 
    {l=$0} 
    ' v="$value" logfile 

2013-10-31 07:29:34.415 INFO - TTT153|Receive|0000131|.... 
2013-10-31 07:30:34.473 INFO - TTT153|Receive|0000131|.... 

将其保存到一个变量

res=$(awk ' 
    { 
    split($1,a,"-") 
    split($2,b,"[:.]") 
    t1=mktime(a[1] " " a[2] " " a[3] " " b[1] " " b[2] " " b[3]) "." b[4] 
    split(v,c,"[- :.]") 
    t2=mktime(c[1] " " c[2] " " c[3] " " c[4] " " c[5] " " c[6]) "." c[7] 
    } 
    t1>t2 {print l "\n" $0;exit} 
    {l=$0} 
    ' v="$value" logfile) 

echo "$res" 
2013-10-31 07:29:34.415 INFO - TTT153|Receive|0000131|.... 
2013-10-31 07:30:34.473 INFO - TTT153|Receive|0000131|.... 
+0

我之前没有使用'awk',我无法在脚本中形成这个脚本部分。这只是遵循这样 '的awk“{上面的整个行代码}” V =“$值”文件' 这里,“文件”应该代表通过日志文件名。我对么 ? – Nish

+0

是'file'是'logfile'我已更新帖子以显示如何将其存储到变量。 – Jotne

+0

是因为#!/ bin/ksh吗? (awk的原因:函数mktime未定义) – Nish