Search code examples
sortingls

ls fails to order files in desired way


I have a script that creates files with output_#.root where # is a number. When I do ls in the directory, it chooses to order the files in a weird way:

output_1.root
output_10.root
output_100.root
output_11.root
output_2.root

etc.

How do I make it order the files in the logical order 1, 2, 3, etc.


Solution

  • Your files are sorted by alphabetical order. It's normal behavior. If you want to sort them by numerical order, you can try this:

    ls *.root | sort -k2 -t_ -n
    

    This will split your result using _ as a separator, and order by numerical order -n based on the second field -k2.