Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort Date/Time in Unix

Input

2012-07-24 10:05:08 AM
2012-07-26 10:13:58 AM
2012-07-24 10:13:58 AM
2012-07-24 10:57:50 AM
2012-07-24 11:15:03 AM
2012-07-24 11:26:08 PM
2012-07-25 11:26:08 PM

Desired Output

2012-07-24 10:05:08 AM
2012-07-24 10:13:58 AM
2012-07-24 10:57:50 AM
2012-07-24 11:15:03 AM
2012-07-24 11:26:08 PM
2012-07-25 11:26:08 PM
2012-07-26 10:13:58 AM

Code I tried

 sort -t ":" -k 1 -k 2 -k 3 Input.txt | sort -t " " -k 3

But I am not getting desired output.

Can anyone suggest anything?


I wrote a code... but still problem persists...

Code

 sed 's/ 12:/00:/g' Input.txt | sort -k 1,1 -k 3,3 -k 2,2 | sed 's/00:/12:/g'

First change 12:43:01 AM to 00:43:01 AM....and then apply sort command.

like image 459
Debaditya Avatar asked Dec 15 '22 21:12

Debaditya


1 Answers

Convert to Epoch Seconds for Sorting

Assuming that your data is stored in /tmp/foo, you can convert the timestamp into a numerically-sortable format with GNU date. For example:

date -f /tmp/foo '+%s' | sort |
while read; do
    date -d "@$REPLY" "+%F %I:%M:%S %p"
done

This should correctly handle the sort in all cases, and especially the cases where all AM times should come before all PM times on the same date. For example, 12:01 AM is now listed before 10:00 PM.

like image 92
Todd A. Jacobs Avatar answered Dec 18 '22 09:12

Todd A. Jacobs