14

How do I make ls sort by file type (e.g. directories first and then by file extension)? The answers suggested in (Super User) Make ls sort by file type result in unknown option errors from ls.

  • 2
    Minor correction regarding your title: ls isn't a bash command; it's a standalone executable located at /bin/ls . – bneely Feb 10 '12 at 7:04
20

As you've found out, the Darwin version of the ls command doesn't support the -X | --sort=extension option. This option is unique to the GNU version of ls.

You can obtain the GNU version of ls for your system. The easiest way to do this is through the Homebrew package manager and porting system. With Homebrew installed do:

brew install coreutils

to add the GNU Core Utilities package to your system. All the utilities will be prefixed with g so they don't collide with the default Darwin utils that OS X ships with.

With the GNU Core Utilites installed you can now do:

gls -X

And you'll see the output sorted as you desire.

If you want to use the GNU Core Utils instead of the utilities that come with OS X you can put the following line in your ~/.bashrc file:

source /usr/local/Cellar/coreutils/8.14/aliases

And you won't need to use the g prefix on the commands any more. I'll say this isn't an entirely safe thing to do as some of the GNU utils differ from the bash built-ins and Darwin tools in how they behave, enough so that they might screw up other things in your shell session. So do this with caution.

1

Based on an answer in the linked Super User article:

ls -l |sort -d -k 1.1,1.1r -k 9 | cut -c 50-

If you want to see the whole output of ls -l, just leave out the cut part.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .