Search code examples
bashls

Sort files with specific order


I have files like

file_fooX_barY_tests.txt

how can I list them in incremental after looping first on 'foo' and then looking in the number following 'bar' ? ie

file_foo100_bar1_test.txt
file_foo100_bar100_test.txt
file_foo100_bar150_test.txt
file_foo200_bar1_test.txt
file_foo200_bar100_test.txt
file_foo200_bar250_test.txt

doing a standard ls, list for example

file_foo100_bar100_test.txt
file_foo100_bar150_test.txt
file_foo100_bar1_test.txt

so, the 'bar100' and 'bar150' come before 'bar1'

thanks


Solution

  • I think sort -V would do just the trick. It is meant to sort by "version order".

    Example :

    $ echo """file_foo100_bar150_test.txt
    file_foo100_bar1_test.txt
    file_foo200_bar250_test.txt
    file_foo200_bar100_test.txt
    file_foo200_bar1_test.txt
    file_foo100_bar100_test.txt
    """ | sort -V
    
    file_foo100_bar1_test.txt
    file_foo100_bar100_test.txt
    file_foo100_bar150_test.txt
    file_foo200_bar1_test.txt
    file_foo200_bar100_test.txt
    file_foo200_bar250_test.txt