Issue
Trying to sort lines in a file. The column1 is HH:MM:SS format and col2 is AM/PM. Need to arrange lines from AM to PM firstly and then progressive time.
11:36:48 AM col3 ...
11:32:00 AM col3 ...
03:18:54 PM col3 ...
02:26:40 PM col3 ...
01:51:56 PM col3 ...
12:55:58 PM col3 ...
11:58:48 AM col3 ...
09:38:41 AM col3 ...
Final:
09:38:41 AM col3 ...
11:32:00 AM col3 ...
11:36:48 AM col3 ...
11:58:48 AM col3 ...
12:55:58 PM col3 ...
01:51:56 PM col3 ...
02:26:40 PM col3 ...
03:18:54 PM col3 ...
Thanks
Solution
You can generate a 24H equivalent of your AM/PM times and prepend it to the line with awk
. Then sort
will work fine and all that's left to do is to strip the added data (with sed
or cut
or whatever):
awk -F '[ :]' '
{
H24 = ($1 == 12 ? ($4 == "AM" ? 0 : 12) : ($4 == "PM" ? $1 + 12 : $1))
print sprintf("%02d%02d%02d", H24, $2, $3), $0
}
' data.txt |
sort |
sed 's/[^ ]* //'
Answered By - Fravadona Answer Checked By - Senaida (WPSolving Volunteer)