Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sub-sorting without losing original sort order?

I have a bunch of files in a folder with a common naming structure that looks something like this:

FOOBAR_1A.8_Alice.pdf
FOOBAR_1A.9_Bob.pdf
FOOBAR_1B.10_Foo.pdf
FOOBAR_1B.11_Bar.pdf
FOOBAR_1B.12_Jack.pdf
FOOBAR_1B.1_Jill.pdf
FOOBAR_1B.2_John.pdf
FOOBAR_1B.3_Mary.pdf

To achieve the above sort order, I have a first sort iteration that looks like this:

find . -type f -name "*.pdf" -print | cut -d'/' -f2 | sort

But as you can see, 10/11/12 is printed before 1/2/3.

I tried piping back into sort again:

find . -type f -name "*.pdf" -print | cut -d'/' -f2 | sort | sort -t '.' -k 2n

But this messes up the prior sorting efforts and prints output that looks like:

FOOBAR_1A.7_Alice.pdf
FOOBAR_1B.7_Bob.pdf
FOOBAR_2A.7_John.pdf
FOOBAR_2B.7_Mary.pdf
FOOBAR_2C.7_Foo.pdf
FOOBAR_1A.8_Bar.pdf
FOOBAR_1B.8_Jack.pdf
FOOBAR_2A.8_Jill.pdf

So, to summarise, my desired sorting output is :

  1. FOOBAR_NA.N should be sorted numerically for the first character (i.e. FOOBAR_1 then FOOBAR_2 etc.)
  2. FOOBAR_NA.N should then be sorted alphabetically by the second character (i.e. FOOBAR_1A then FOOBAR_1B etc.)
  3. FOOBAR_NA.N should finally be sorted by the number after the first dot (i.e. FOOBAR_1A.1 then FOOBAR_1A.2 etc.)
like image 845
Little Code Avatar asked Feb 18 '26 21:02

Little Code


1 Answers

You can try -V (sort by version):

find . -name '*.pdf' | cut -d'/' -f2 | sort -t _ -k2V

FOOBAR_1A.8_Alice.pdf
FOOBAR_1A.9_Bob.pdf
FOOBAR_1B.1_Jill.pdf
FOOBAR_1B.2_John.pdf
FOOBAR_1B.3_Mary.pdf
FOOBAR_1B.10_Foo.pdf
FOOBAR_1B.11_Bar.pdf
FOOBAR_1B.12_Jack.pdf
like image 81
anubhava Avatar answered Feb 20 '26 14:02

anubhava



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!