質問

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"},
役に立ちましたか?

解決

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

他のヒント

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.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top