Using sort with alphanumeric filenames

sort

I'm sorting the results of a find command which finds all of the files in the current directory:

find . -maxdepth 1 -type f -iname "*.flac" | sort

What I'm expecting is a list like this:

./Track 1.flac
./Track 2.flac
./Track 3.flac
...
./Track 9.flac
./Track 10.flac
./Track 11.flac

What I'm getting is a list like this:

./Track 10.flac
./Track 11.flac
./Track 1.flac
./Track 2.flac
./Track 3.flac
...
./Track 9.flac

Is there an option to sort which will put them in alphanumeric ascending order so that numbers are evaluated properly?

Best Answer

Try to pass the -n and -k2 command line options to sort. I.e.,

find . -maxdepth 1 -type f -iname "*.flac" | sort -n -k2

When I put your unsorted filenames into file 'data.txt' and run this command:

sort -k2 -n data.txt

I get this as output:

./Track 1.flac
./Track 2.flac
./Track 3.flac
./Track 9.flac
./Track 10.flac
./Track 11.flac

explanation of options:

-n (numeric sort) compare according to string numerical value
-k2 means sort on the 2nd field (and to the end of the line), 
    you could just restrict it to the second field with -k2,2

You didn't ask about this, and I didn't use it above, but it may come in handy some day.

-r reverse sort order 

man page for sort

See my related post on SO about sorting according to different fields Sort by third column leaving first and second column intact (in linux) which explains more about the sort command.

Related Question