2013-06-27 66 views
2

如何通過asc或desc命令從特定列的日期和時間或僅日期列重新排序文件。如何通過特定列的asc或desc命令重新排序文件

{"hostname":"sg2","role":"epay","eventid":"ALERT_ORACLE","date":"02/08/2011","time":"01:30:00"}, 
{"hostname":"sg1","role":"pay","eventid":"ALERT_DF","date":"11/24/2010","time":"19:33:01"}, 
{"hostname":"sg3","role":"ipay","eventid":"ALERT_SMF","date":"12/11/2012","time":"02:30:00"}, 

通常用「之類的-gk(列數)」,在這種情況下,不能夠趕上日期和時間列或僅日期,也許是需要一些分隔字符串或相關。

Expetected的看法是:

{"hostname":"sg1","role":"pay","eventid":"ALERT_DF","date":"11/24/2010","time":"19:33:01"}, 
{"hostname":"sg2","role":"epay","eventid":"ALERT_ORACLE","date":"02/08/2011","time":"01:30:00"}, 
{"hostname":"sg3","role":"ipay","eventid":"ALERT_SMF","date":"12/11/2012","time":"02:30:00"}, 

回答

3

你的生活會更容易,如果你選擇了一個ISO日期格式(YYYY-MM-DD),但

sort_by_date() { 
    awk -F \" '{ 
     split($16, date, "/") 
     split($20, time, ":") 
     timestamp = mktime(date[3]" "date[1]" "date[2]" "time[1]" "time[2]" "time[3]) 
     print timestamp "\t" $0 
    }' "$1" | 
    sort -k1,1n | 
    cut -f2- 
} 
sort_by_date filename 

降序,使用sort -k1,1nr

+0

很好的例子,那就是我需要的,謝謝 –

3

使用sort:作爲分隔符和命令通過5M列日期比較:

$ sort -t: -k5M file 
{"hostname":"sg1","role":"pay","eventid":"ALERT_DF","date":"11/24/2010","time":"19:33:01"}, 
{"hostname":"sg2","role":"epay","eventid":"ALERT_ORACLE","date":"02/08/2011","time":"01:30:00"}, 
{"hostname":"sg3","role":"ipay","eventid":"ALERT_SMF","date":"12/11/2012","time":"02:30:00"}, 

來源:Sort logs by date field in bash

相關問題