Reputation: 191
I created three files in a directory with the following names:
11 13 9
The problem: As I created file 9
after 13
, it is placed after file 13
when I do the ls
command.
How can I make the ls
command sort the files in the numerical order, like in the following?
9 11 13
Upvotes: 16
Views: 16488
Reputation: 6620
If you're on macOS where, as @eris points out, -v
isn't supported, you can pipe the output to sort
to achieve what you want:
ls -1 | sort -n
Note that's the digit 1, not a lowercase L.
ls -1
lists one file per line, but without the additional columns of -l
. This makes it suitable for piping into sort
, where -n
is a shorthand for --numeric-sort
: "compare according to string numerical value"
Upvotes: 0
Reputation: 1770
Look at the man page for ls
.
From there-
-v natural sort of (version) numbers within text.
You'll find that the command ls -v
does what you want.
If you want the file names on different lines then you can do ls -1v
.
Upvotes: 24
Reputation: 9157
Unfortunately, ls -v
on macOS and FreeBSD does not perform a natural sort on the list of files. FreeBSD ls does not support this flag at all. On macOS it can be used to
force unedited printing of non-graphic characters; this is the default when output is not to a terminal.
If you badly need the GNU extension of -v
to the ls utility, you can install the GNU ls and then use alias ls=gls
to use the GNU ls instead of the default ls. GNU ls usually comes with the coreutils
package, so, e.g.,
brew install coreutils
pkg install coreutils
Upvotes: 3