Search code examples
filebashsortinggnomels

Bash sort by file name like GNOME does


Bash is really annoying me with the way that it sorts it's files with the sort command and can't seem to find a way around this. When I sort the files with GNOME though by name, it shows it exactly how I want. I'm trying to sort by real order but the 10's and 1's mess everything up when sorting in bash. Here's how bash sorts a sample of my files:

HeadsetBatteryBG_10@2x.png
HeadsetBatteryBG_11@2x.png
HeadsetBatteryBG_12@2x.png
HeadsetBatteryBG_1@2x.png
HeadsetBatteryBG_13@2x.png
HeadsetBatteryBG_14@2x.png
HeadsetBatteryBG_15@2x.png
HeadsetBatteryBG_16@2x.png
HeadsetBatteryBG_17@2x.png
HeadsetBatteryBG_2@2x.png
HeadsetBatteryBG_3@2x.png
HeadsetBatteryBG_4@2x.png
HeadsetBatteryBG_5@2x.png
HeadsetBatteryBG_6@2x.png
HeadsetBatteryBG_7@2x.png
HeadsetBatteryBG_8@2x.png
HeadsetBatteryBG_9@2x.png

I see what it's doing here, but is there anywhere to sort a list like this in bash how it SHOULD be sorted? With the numbers in real numerical order instead of this strange thing that it's doing.


Solution

  • Try

    sort -k2 -t_ -n [file]
    

    That will sort numerically (-n) on the 2nd field (-k2) using _ as the field separator (-t_).

    (Shamelessly stolen from SuperUser)