I would - as I often do - suggest perl
.
perl
has a sort function that lets you specify a comparison function. This comparison function is any test that takes two values, and returns -1
, 0
or 1
depending on relative position.
It iterates the list setting each value as $a
and $b
and 'doing the test' for each element.
So by default:
$a cmp $b
for stringwise comparison, or sort { $a <=> $b }
for numeric.
But as a result, you can apply arbitrarily complex custom sort criteria:
#!/usr/bin/perl
use strict;
use warnings;
sub sort_by_sc {
my ( $a_sc ) = $a =~ m/SC(\d+)/;
my ( $b_sc ) = $b =~ m/SC(\d+)/;
return $a_sc <=> $b_sc;
}
my @file_list = qw (
ABC38388.SC01.StatueGrade_MKP
ABC38388.SC02.Statue_GKP
DEF38389.SC03.Statue_HKP
XYZ38390.SC00.Statue_WKP
);
print sort sort_by_sc @file_list;
Or reduced to a one liner, reading STDIN
or a file (linefeed delimited, which is usually good enough):
perl -e 'print sort {@x = map {/SC(\d+)/}($a,$b); $x[0] <=> $x[1]} <>'
You could instead feed it the result of glob
of a directory pattern instead:
perl -e 'print sort {@x = map {/SC(\d+)/}($a,$b); $x[0] <=> $x[1]} glob ( "*SC*")'
-t.
tells it to use.
as the field separator so the-k2
refers to the second field as defined by.
. – terdon Dec 09 '15 at 17:48