Sort -t: -k1

My file1.txt looks like below:

Feb 03 15:58:27 2020
Feb 03 16:01:23 2020
Feb 03 16:11:29 2020
Feb 04 11:01:49 2020
Jan 20 16:27:38 2020
Jan 20 16:29:51 2020
Jan 20 16:44:39 2020
Jan 20 16:56:41 2020

I tried: sort -t: -k1 and result below:

Feb 03 15:58:27 2020
Feb 03 16:01:23 2020
Feb 03 16:11:29 2020
Feb 04 11:01:49 2020
Jan 20 16:27:38 2020
Jan 20 16:29:51 2020
Jan 20 16:44:39 2020
Jan 20 16:56:41 2020

I'd like to have Feb 04 11:01:49 2020 as the last line.
Thanks in advance!

--- Post updated at 07:02 PM ---

I tried sort -nrz and result below. close but not in order:

Jan 20 16:56:41
Feb 03 16:11:29
Jan 20 16:27:38
Jan 20 16:29:51
Feb 03 15:58:27
Feb 03 16:01:23
Jan 20 16:44:39
Feb 04 11:01:49

To sort dates it works best to convert them to epoch seconds - the number of seconds since Jan 1 970. This code adds an epoch time sorts based on the epoch time, then prints the original minus the seconds: this assumes some kin of linux OS -

while read dt 
do   
   echo $(date -d "$dt" +%s) $dt;    
 done <  file | sort -k1n | awk '{printf("%s %s %s %s\n", $2, $3, $4, $5) }'

Called a tag sort.
I get this output:

Jan 20 16:27:38 2020
Jan 20 16:29:51 2020
Jan 20 16:44:39 2020
Jan 20 16:56:41 2020
Feb 03 15:58:27 2020
Feb 03 16:01:23 2020
Feb 03 16:11:29 2020
Feb 04 11:01:49 2020

--- Post updated at 17:16 ---

@Drl - one of our senior people, may mention getting a linux package for date operations, one of the commands is "dsort" which does exactly what the code above does. Hopefully he will mention where to download it. I do not know

2 Likes

Some sort versions - my is

$ sort --version
sort (GNU coreutils) 8.30
  • offer the option ( man sort )

so it would yield

$ sort -M file
Jan 20 16:27:38 2020
Jan 20 16:29:51 2020
Jan 20 16:44:39 2020
Jan 20 16:56:41 2020
Feb 03 15:58:27 2020
Feb 03 16:01:23 2020
Feb 03 16:11:29 2020
Feb 04 11:01:49 2020
2 Likes

Using RudiC's suggestion of -M , using GNU sort

sort -k4n -k1,1M -k2,3n file

Would complete the sort.

1 Like

sort -k4n -k1,1M -k2,3n file worked perfectly. Thank you so much!

Hi.

The code is available in some repositories (I just installed it in a VM for Debian Buster), and also at github, as newer versions 0.4.3 .. 0.4.7:

dateutils.dsort Sort contents of FILE chronologically. (man)
Path    : /usr/bin/dateutils.dsort
Package : dateutils
Home    : http://www.fresse.org/dateutils
Version : 0.3.1
Type    : ELF 64-bit LSB shared object, x86-64, version 1 ( ...)
Help    : probably available with -h,--help
Home    : https://github.com/hroptatyr/dateutils (doc)

This is from my system:

OS, ker|rel, machine: Linux, 3.16.0-7-amd64, x86_64
Distribution        : Debian 8.11 (jessie) 

ALthough this has been solved, if I get some time I'll try to post a solution with dateutils ... cheers, drl