Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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?

share|improve this question
add comment

2 Answers

up vote 10 down vote accepted

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. Hope this helps.

share|improve this answer
add comment

In zsh, use the n globbing qualifier:

print -l *.flag(n)
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.