I have a list of names, which are out of order. How can I get them in the correct alphanumeric order, using a custom sort order for the alphabetical part?
My file numbers.txt
:
alpha-1
beta-3
alpha-10
beta-5
alpha-5
beta-1
gamma-7
gamma-1
delta-10
delta-2
The main point is that my script should recognize that it should print alpha
before beta
, and beta
before gamma
, and gamma
before delta
.
That is, the words should be sorted based on the order of the letters in the Greek alphabet they represent.
Expected order:
alpha-1
alpha-5
alpha-10
beta-1
beta-3
beta-5
gamma-1
gamma-7
delta-2
delta-10
PS: I tried with sort -n numbers.txt
, but it doesn't fit my need.
Here's a Python solution. Don't try to do hard things with Bash, sed, awk. You can usually accomplish what you want, but it'll be more confusing, more error prone, and harder to maintain.
If you have access to awk and sed then try this
Adding changes for Greek ordering..
I would reach for Perl here. This script will work:
Save the Perl code into a file (say,
greeksort.pl
) and runperl greeksort.pl numbers.txt
to get your sorted output.Generic solution: sort -t- -k 1,1 -k 2,2n numbers.txt
Below script will work for custom requirement. It is not the best solution. Result will be again stored in numbers.txt
You can use an auxiliary
awk
command as follows:The
awk
command is used to:map the custom keys onto numbers that reflect the desired sort order; note that the full list of keys must be passed via variable
keysInOrder
, in order.prepend the numbers to the input as an auxiliary column, using separator
-
too; e.g.,beta-3
becomes2-beta-3
, becausebeta
is in position 2 in the ordered list of sort keys.sort
then sortsawk
's output by the mapped numbers as well as the original number in the 2nd column, yielding the desired custom sort order.cut
then removes the aux. mapped numbers again.yeah, use an actuall shell and non-gnu userland commands. not much easier to code in the first place but at least won't be prone to random bugs introduced by idiotic maintainers who do not have a clue regarding backwards compatibility