Home » Questions » Computers [ Ask a new question ]

How to sort first directories then files etc… when using “ls” in Unix

How to sort first directories then files etc… when using “ls” in Unix

I would like to use the ls command to first show directories and then files. I tried:

Asked by: Guest | Views: 97
Total answers/comments: 5
Guest [Entry]

"The following command will list directories first, ordinary files second, and links third.

ls -la | grep ""^d"" && ls -la | grep ""^-"" && ls -la | grep ""^l""

Also, it would make a great deal of sense to create an alias for this command to save keystrokes.


If you want directories first, and then everything that is not a directory second, use this:

ls -la | grep ""^d"" && ls -la | grep -v ""^d"""
Guest [Entry]

"For the mac users, you can install coreutils.
This formula provides the GNU core utilities implementations, and for the commands that are also provided by macOS, they have been installed with the ""g"" prefix.
brew install coreutils
gls --color -h --group-directories-first

You can further simplify your life with an alias
alias ls='gls --color -h --group-directories-first'"
Guest [Entry]

"To delerious010's answer, I would add that if you want old-style ordering:

LANG=C ls -la --group-directories-first

(or use LC_ALL or LANGUAGE or LC_COLLATE set to ""C"").

This will give something similar to:


Although, if I recall correctly, the hidden dot files originally appeared before the directories."
Guest [Entry]

"Here's a function to do this (bash or zsh):
And... I'm not suggesting this is the best way, but it's the one I came up with and am using right now:

function lss
# Shows directory listing with directories at the top.

command ls --color=always $@ | egrep '^d|total'
command ls --color=always $@ | egrep -v '^d|total';
Guest [Entry]

"ls -laX will show you directories first in alphabetical order, but will screw the file list.

Long options:

-l # List
-X # Sort alphabetically by entry extension"