Sort part of the name

filenames

I have multiple names that have the same prefix but the prefix is unknown.

I want to sort only by the digits in the name.

i.e

abcd_006-123
abcd_006-232
bbcd_w_006-112

so bbcd_w_006-112 should be the first

thanks

Best Answer

With zsh, you could define a glob sorting function like:

digitsOnly() REPLY=${REPLY//[^0-9]} # removes all non-digits

and then use it as:

print -rC1 -- *(no+digitsOnly)

There, the n glob qualifier turns the numericglobsort option for that one glob extension, and o+function sorts based on the output (via $REPLY) of the function.

print -rC1 prints its arguments raw on 1 column.

Remember that if you use ls, ls does sort the list of files before printing (alphabetically by default). With the GNU implementation of ls, that sorting can be avoided with the -U option:

ls -ldU -- *(no+digitsOnly)

You can do something similar with perl with:

perl -le 'sub digitsOnly {$_=shift; s/\D//gr};
          print for sort {digitsOnly($a) <=> digitsOnly($b)} <*>'

Or to run a command on that list of files:

perl -l0e 'sub digitsOnly {$_=shift; s/\D//gr};
           print for sort {digitsOnly($a) <=> digitsOnly($b)} <*>' |
   xargs -r0 ls -ldU --
Related Question