2

How can reorder a file by asc or desc order from specific column date and time or only date column.

{"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"},

Usually use "sort -gk (column number)" in that case not able to catch date and time column or only date, maybe is need some separator string or related.

Expetected view is:

{"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"},
Kalin Borisov
  • 1,091
  • 1
  • 12
  • 23

2 Answers2

3

Use sort with : as delimiter and order by column 5M for date comparison:

$ 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"},

Source: Sort logs by date field in bash.

Community
  • 1
  • 1
fedorqui
  • 275,237
  • 103
  • 548
  • 598
3

Your life would be easier if you had chosen an ISO date format (YYYY-mm-dd), but

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

For descending, use sort -k1,1nr

glenn jackman
  • 238,783
  • 38
  • 220
  • 352