Sort order explanation

osxsortterminal

Giving a lot of files, sort -n gives me this result:

f1.txt
f10.txt
f2.txt

which doesn't seem right to me. What is the explanation?

Can I get this by default:

f1.txt
f2.txt
f10.txt

Best Answer

I recommend to use rather

sort -V data.txt

-V stands for "version sort" and it basically handles correctly both alphabetical and numerical characters, so that if you would have more files, say:

f1.txt
f10.txt
f2.txt
a1.txt
a10.txt
a2.txt

then sort -V will give you

a1.txt
a2.txt
a10.txt
f1.txt
f2.txt
f10.txt

whereas sort -k 1.2n or sort -n -k 1.2:

a1.txt
f1.txt
a2.txt
f2.txt
a10.txt
f10.txt