I have these lines in a file:
Oct 29 23:14:39
Oct 30 19:45:15
Oct 31 13:15:19
Nov 1 10:34:15
Nov 2 18:39:20
Nov 3 12:34:59
Nov 4 16:34:59
Nov 5 20:34:59
When I run sort -r -k2
it gives me the following:
Nov 5
Nov 4
Nov 3
Oct 31
Oct 30
Oct 29
Nov 2
Nov 1
How do I get it like so:
Nov 5
Nov 4
Nov 3
Nov 2
Nov 1
Oct 31
Oct 30
Oct 29
Would appreciate any pointers, comments, advices at all. Do I also need to sort on months in reverse order? How? -M -r?
CodePudding user response:
This works well!
sort -k1Mr -r -k2nr file.txt
file.txt content
Oct 6 20:34:59
Oct 29 23:14:39
Oct 30 19:45:15
Oct 31 13:15:19
Nov 1 10:34:15
Nov 2 18:39:20
Nov 3 12:34:59
Nov 4 16:34:59
Nov 5 20:34:59
Output:
Nov 5 20:34:59
Nov 4 16:34:59
Nov 3 12:34:59
Nov 2 18:39:20
Nov 1 10:34:15
Oct 31 13:15:19
Oct 30 19:45:15
Oct 29 23:14:39
Oct 6 20:34:59
NOTE:
The following answers fail to sort the entry Oct 6 20:34:59
if exists.
sort -k1,1 -k2r,2
sort -rM
CodePudding user response:
The arrangement of the fields is lucky, in that the primary one comes first, and the secondary one second (and the rest of the line doesn't matter because you have at most one entry per day). But your example has only Oct
and Nov
, and I don't think you ought to rely on that. If you add e.g. Aug 7
you'll need a more robust solution. I suggest:
sort -rM
That is, sort in the default way (by the first field, then by the second), treat any month abbreviation found as a month abbreviation, and reverse the whole thing.
CodePudding user response:
Assuming the dates are sorted in the file, just reverse the line order:
tac file
CodePudding user response:
This works for me:
sort -k1Mr,1 -k2r,2
month-sorted by field #1 reversely, then sorted by field #2 reversely
Nov 5 20:34:59
Nov 4 16:34:59
Nov 3 12:34:59
Nov 2 18:39:20
Nov 1 10:34:15
Oct 31 13:15:19
Oct 30 19:45:15
Oct 29 23:14:39
Edit:
A key specification like -k2
means to take all the fields from 2 to the end of the line into account.
To sort by a single column, use -k2,2
as the key specification. This means to use the fields from #2 to #2, i.e. only the second field.
man sort
-k, --key=KEYDEF
sort via a key; KEYDEF gives location and type
...
KEYDEF is F[.C][OPTS][,F[.C][OPTS]] for start and stop position, where
F is a field number and C a character position in the field; both are
origin 1, and the stop position defaults to the line's end.