How to sort the output of `ls`?

Use the switch -v [natural sort of (version) numbers within text]

ls -v

The output is sorted. According to the ls manpage:

Sort entries alphabetically if none of -cftuvSUX nor --sort is specified.

But if you want to go further, you have at least two options:

Option 1 - ls sort switches

man ls tells you about a number of switches you can use to sort, specifically, the ls man page says:

none (-U), size (-S), time (-t), version (-v), extension (-X)

In your case, you want "version" sort (-v). Be careful, though, since this will also sort anything that has a blahblah-X.Y.Z-A arrangement which may not be entirely what you want. See also GNU's explanation of version sort.

Option 2 - Pipes to sorting commands

You could use a pipe | to send the output to another command, for example the command sort which you could use to sort in a number of other ways, as in ls -1 | sort -n which is useful if you have numbered files. The -1 switch ensures that the output is one-line-per-file.

Equally, you can manipulate the output to aid with sorting by using things like sed or awk.

There are plenty of ways to answer this sort of* question. You may find a linux shell tutorial helpful.

*(See what I did there? :-p)


As already pointed out in a comment, the output is already sorted, but by characters, not numbers. You may want to pipe the output of ls through sort which has a switch to sort by numbers within strings:

ls | sort --version-sort

From the manpage:

-V, --version-sort
         natural sort of (version) numbers within text

Downside: When we issue ls then it outputs the files in a table with as many columns as fit on the current screen (just like you showed in your post). But when ls notices that its output is redirected to a file or to a pipe (as in ls | sort) then ls prints the files in just one column because it then assumes the output is to be processed line-by-line (aka file-by-file) by some other program (like sort). So the output of ls | sort -V will be in one column instead of in a table with multiple columns. See @vijay's simple but perfect answer for how to avoid that.