2013-10-31 134 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