Shell – Sort an output by year month and date

datelinuxshell-scriptsort

I want to sort the output below by year, month and date. I tried a few combinations that don't seem to be working.

In the below output 2nd column is the date, 3rd is the month and 4th is the year.

I tried to apply the sort command this way:

sort -nk2 -Mk3 -nk4

but it didn't work because I got the error

sort: options '-Mn' are incompatible

Here's my sample datafile

adcblz01 14 Mar 2018  
adcblz03 23 Nov 2018  
aktestlb02 26 Aug 2019    
ckicbrwlz1 23 Mar 2018   
ckilabbrwlb1 23 Mar 2018   
bhuiflz28 09 Mar 2017  
bhuiflz47 09 Mar 2017  
bhuiflz48 09 Mar 2017  
olkeflb24 23 Jul 2019  
olkeflz46t2 09 Mar 2017  
rrjugflb7 03 Jul 2019

Best Answer

You're close, but you've got the order of the sort operations wrong at two levels

  1. You should sort by year (field 4), then by month (field 3), and finally by day (field 2)
  2. You should apply the sort qualifiers (n and M) just to the keys, not globally

The resulting sort command is thus,

sort -k4n -k3M -k2n
Related Question