gnu-sort

Primary and secondary numerical sorting of file names by delimiter


I have some files named like so:

S241R39.txt
S241R40.txt
S241R41.1.txt
S241R41.2.txt
S241R42.1.txt
S241R42.2.txt

I want to be able to sort these in this order:

S241R39.txt
S241R40.txt
S241R41.1.txt
S241R42.1.txt
S241R41.2.txt
S241R42.2.txt

Here, I want 41.1 to come before 42.1, and 42.1 to come before 41.2

In files that don't end in .1 or .2 this sorts my files correctly:

ls -1 *.txt | sort -V

Does anyone have any suggestions for how I can adjust this to give me my desired output?


Solution

  • You can use sort -t . -k2n -k1n:

    printf '%s\n' *.txt | sort -t . -k2n -k1V
    
    S241R39.txt
    S241R40.txt
    S241R41.1.txt
    S241R42.1.txt
    S241R41.2.txt
    S241R42.2.txt
    

    sort command in use is: