-1

I want to sort a file alphanumerically but with priority for the numbers in each file entry. Example: File is:

22 FAN
14 FTR
16 HHK
19 KOT
25 LMC
22 LOW
22 MOK
22 RAC
22 SHS
18 SHT
20 TAP
19 TAW
23 TWO
15 UNI

I want to sort it as:

25 LMC
23 TWO
22 FAN
22 LOW
22 MOK
22 RAC
22 SHS
20 TAP
19 KOT
19 TAW
18 SHT
16 HHK
15 UNI
14 FTR
  • @MadisonCourto I disagree. He's asking for a way to sort in reverse order for one field, and in natural (ascending) order for the second one, in case the first keys are the same. See my posted answer below. – mjuarez Oct 17 '18 at 06:15
  • 2
    Possible duplicate of [How to combine ascending and descending sorting?](https://stackoverflow.com/q/31508836/608639), [Sorting multiple keys with Unix sort](https://stackoverflow.com/q/357560/608639), [Sorting according to field's numerical value in Bash](https://stackoverflow.com/q/4856030/608639), etc. – jww Oct 17 '18 at 06:28
  • @mjuarez sorry, what do you disagree with? – Madison Courto Oct 17 '18 at 23:20

2 Answers2

2

So, basically, you're asking to sort the first field numerically in descending order, but if the numeric keys are the same, you want the second field to be ordered in natural, or ascending, order.

I tried a few things, but here's the way I managed to make it work:

   sort -nk2 file.txt  | sort -snrk1

Explanation:

  • The first command sorts the whole file using the second, alphanumeric field in natural order, while the second command sorts the output using the first numeric field, shows it in reverse order, and requests that it be a "stable" sort.

  • -n is for numeric sort, versus alphanumeric, in which 6 would come before 60.

  • -r is for reversed order, so from highest to lowest. If unspecified, it will assume natural, or ascending, order.
  • -k which key, or field, to use for sorting order.
  • -s for stable ordering. This option maintains the original record order of records that have an equal key.
mjuarez
  • 14,655
  • 10
  • 52
  • 65
1

There is no need for a pipe, or the additional subshell it spawns. Simply use of keydef for both fields 1 and 2 will do:

$ sort -k1nr,2 file

Example/Output

$ sort -k1nr,2 file
25 LMC
23 TWO
22 FAN
22 LOW
22 MOK
22 RAC
22 SHS
20 TAP
19 KOT
19 TAW
18 SHT
16 HHK
15 UNI
14 FTR
David C. Rankin
  • 69,681
  • 6
  • 44
  • 72