Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I would like to use ls command to first show direcotries and then files. I tried

ls -la | sort -k 1

But I got a wrong order.

share|improve this question
    
it's because - comes before d when using sort – Nifle Feb 16 '10 at 13:32
3  
Old time unix heads (the ones from the pre-GUI age) used to capitalize their folder names and make plain-file names uncapitalized to get that result automagically. – JRobert Jun 18 '12 at 17:43

11 Answers 11

up vote 15 down vote accepted

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.

Edit:

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"

share|improve this answer
    
This command doesn't list everything if there are, for example, sockets or FIFOs in the folder – Studer Feb 16 '10 at 14:01
1  
That edited version should still work with other types. The first grep says everything that starts with a 'd', and the second says everything that doesn't start with a 'd'. Surely everything either starts with a d or doesn't, right? – Ry4an Aug 24 '12 at 12:58
    
To make the first one show other files too: ls -la | grep "^d" && ls -la | grep "^-" && ls -la | grep -E "^d|^-" -v | grep -v "^total" – Mark Apr 26 '13 at 22:25
1  
@Mark -- Why not just do: ls -la | grep "^d" && ls -la | grep "^-" && ls -la | grep -v -E "^d|^-|^total"? – FCTW Aug 19 '13 at 3:22
1  
To make @FCTW's command an OSX alias, add this to your ~/.profile: alias la="ls -la | grep \"^d\" && ls -la | grep \"^-\" && ls -la | grep -E \"^d|^-\" -v | grep -v \"^total\"" – aliteralmind May 20 '15 at 14:00

There are certain things I want to see in a directory listing, and so far none of the answers here meets all of the requirements below. My requirements for a directory listing:

  1. Directories and files are sorted alphabetically
  2. Directories are listed first
  3. Symbolic links (symlinks) are sorted like files
  4. Sorting is case-insensitive
  5. Sorting ignores all leading non-alpha characters in a filename
  6. Listing includes the total count of directories (excluding ./ and ../), files, and links
  7. Listing includes the total size (disk usage) of directories and files
  8. The listing has to look the same on Linux and Windows (Git Bash shell) -- this was the hardest to get right since convenient options like --group-directories-first don't work in Git Bash for Windows

After much hacking about, I finally came up with a one-liner (albeit a very long line ;-)) that I'm satisfied with. I have assigned this to an alias named 'dir':

ls -dlF --color * .* | head -n2 && ls -AlF | LC_ALL=C grep "^d" | 
LC_ALL=C sort -k 9df && ls -AlF | LC_ALL=C grep "^[l-]" | 
LC_ALL=C sort -k 9df && echo -e `find -maxdepth 1 -type d ! -name . | 
wc -l` Dir\(s\) `du -hs | cut -f 1`\\t\\t`find -maxdepth 1 -type f | 
wc -l` File\(s\) `find -maxdepth 1 -type f -print0 | du -ch --files0-from=- | 
tail -n 1 | cut -f 1`\\t\\t`find -maxdepth 1 -type l | wc -l` Link\(s\)

To make things easier to manage, I came up with separate commands to output each segment of the directory listing to my liking, then assembled them together using the && operator.

  • ls -dlF --color * .* | head -n2 -- Extract ./ and ../. We don't want to pass these through sort because they are already in the correct order, and sorting them can result in ../ being listed first. The -d option is to get rid of the "total" line; I like to add -F to show the trailing slash for directories (it will also mark symlinks with "@" when you do a plain ls -F).

  • ls -AlF | LC_ALL=C grep "^d" | LC_ALL=C sort -k 9df -- Extract the directories and sort them by filename (9th column), ignoring both non-alpha/space characters (d option) and character case (f option). The ls -A option excludes ./ and ../ from the listing since we already extracted them in the previous step. I tend to prefix all grep and sort commands with the LC_ALL=C locale reset so that (1) the output is consistent across Unix shells, and (2) you can sometimes see faster performance since it no longer has the overhead of the heavy UTF-8 character set to deal with.

  • ls -AlF | LC_ALL=C grep "^[l-]" | LC_ALL=C sort -k 9df -- This is similar to the step above, but this time we are sorting files and symlinks.

  • find -maxdepth 1 -type d ! -name . | wc -l -- Get the number of directories, excluding ./ and ../.

  • find -maxdepth 1 -type f | wc -l -- Get the number of files.

  • find -maxdepth 1 -type l | wc -l -- Get the number of symlinks.

  • du -hs | cut -f 1 -- Extract the total size of all subdirectories in human-readable format.

  • find -maxdepth 1 -type f -print0 | du -ch --files0-from=- | tail -n 1 | cut -f 1 -- Extract the total size of all files in human-readable format.

Let's see our new dir alias in action!

BEFORE:

$ ls -alF
total 22
drwxr-xr-x   13 Tom      Administ     4096 Oct 25 02:38 ./
drwxr-xr-x    3 Tom      Administ        0 Dec 24  2014 ../
drwxr-xr-x   15 Tom      Administ     4096 Sep 17 01:23 .VirtualBox/
-rw-r--r--    1 Tom      Administ      615 Oct 25 02:38 .aliases
-rw-r--r--    1 Tom      Administ    12742 Oct 24 11:47 .bash_history
-rw-r--r--    1 Tom      Administ     3234 Oct 24 15:06 .bash_profile
drwxr-xr-x    1 Tom      Administ        0 Jan 24  2015 .gem/
-rw-r--r--    1 Tom      Administ      586 Oct 24 03:53 .gitconfig
drwxr-xr-x    1 Tom      Administ     4096 Dec 28  2014 .ssh/
drwxr-xr-x    4 Tom      Administ        0 Jan 24  2015 .travis/
-rw-r--r--    1 Tom      Administ     6645 Oct 25 02:38 _viminfo
-rw-r--r--    1 Tom      Administ     4907 Oct 24 15:16 profile
drwxr-xr-x    1 Tom      Administ        0 Oct 24 22:20 tmp/

AFTER:

$ dir
drwxr-xr-x   13 Tom      Administ     4096 Oct 25 02:38 ./
drwxr-xr-x    3 Tom      Administ        0 Dec 24  2014 ../
drwxr-xr-x    1 Tom      Administ        0 Jan 24  2015 .gem/
drwxr-xr-x    1 Tom      Administ     4096 Dec 28  2014 .ssh/
drwxr-xr-x    1 Tom      Administ        0 Oct 24 22:20 tmp/
drwxr-xr-x    4 Tom      Administ        0 Jan 24  2015 .travis/
drwxr-xr-x   15 Tom      Administ     4096 Sep 17 01:23 .VirtualBox/
-rw-r--r--    1 Tom      Administ      615 Oct 25 02:38 .aliases
-rw-r--r--    1 Tom      Administ    12742 Oct 24 11:47 .bash_history
-rw-r--r--    1 Tom      Administ     3234 Oct 24 15:06 .bash_profile
-rw-r--r--    1 Tom      Administ      586 Oct 24 03:53 .gitconfig
-rw-r--r--    1 Tom      Administ     4907 Oct 24 15:16 profile
-rw-r--r--    1 Tom      Administ     6645 Oct 25 02:38 _viminfo
      5 Dir(s) 2.8M           6 File(s) 31K           0 Link(s)

One minor downside is that you cannot have colored listings, since the color control characters surrounding the filenames make the sorting too unreliable.

share|improve this answer
    
Great answer! But when you say, “After much hacking about, I finally came up with a one-liner…” Yes, indeed that is not really a “one liner” in the classic sense. It might make sense to take that logic and make it a standalone shell script and just run that or call it as an alias. – JakeGould Oct 24 '15 at 20:11
    
@JakeGould You are fast! I haven't even finished proof-reading my answer yet and you already finished reading it and shot off a comment :). Yeah, it's a prime candidate for a function, but I was too lazy at the time, so just threw it into my .bash_aliases file. On the other hand, I usually only write a function when I cannot do something without passing parameters. – 10basetom Oct 24 '15 at 20:20

By the question, it seems as if the OP is interested in a real file manager that works in the CLI. I recommend Midnight Commander for this, which is a dual-pane full-featured file manager that runs in the CLI and does not require an X server:

Midnight Commander screen shot

On Debian-based systems it can be easily installed:

$ sudo apt-get install mc

On Fedora / RHEL / CentOS:

# yum install mc

Note that Midnight Commander does sort by directories first, then files.

share|improve this answer
    
I don't think OP wanted a CLI filemanager. He wanted to know how to make ls sort directories ahead of files. – joejoe31b Apr 27 '15 at 8:43
    
Midnight Commander does sort by directories first, then files. – dotancohen Oct 1 '15 at 12:33
    
@kenorb: Thank you, I've addressed your concern in an edit. – dotancohen Oct 1 '15 at 12:33

I do so love *nix and love seeing the inventiveness that goes into some of these replies...

Mine's not nearly as fancy on GNU Linux :

alias ls='ls --color -h --group-directories-first'

Given that I'm more comfortable with my linux CLI apps, I tend to also update coreutils on OSX :

brew install coreutils
alias ls='/usr/local/bin/gls --color -h --group-directories-first'
share|improve this answer
3  
unfortunately, this doesn't work on osx terminal, since -- option is not available. – MEM May 20 '12 at 13:30
6  
re love: Is that sarcasm? If so, I'd agree. – allyourcode Jun 2 '12 at 1:06
    
great :) didn't know about the "alias" command :) – Alex Oct 13 '12 at 14:55
3  
Re: Doesn't work on mac ... True enough, personally though I generally do a brew install coreutils to override the mac builtins for my local user. – jonathanserafini Apr 6 '14 at 15:17
1  
Purpose of alias ls is to define the configuration elements I want to use 90% of the time. Less keystrokes to achieve the desired output. If you ever then want to have native ls output you can always /bin/ls. – jonathanserafini Aug 15 '14 at 20:36

For Mac users coreutils:

brew install coreutils

alias ls='ls --color -h --group-directories-first'

Assuming your system is ready to homebrew:

share|improve this answer
1  
gls rather. Right? – Paul Irish Jun 9 '15 at 17:58
1  
Yes, by default. You can also use coreutils by default with PATH="/usr/local/opt/coreutils/libexec/gnubin:$PATH". – benesch Jul 8 '15 at 18:48

This is a script solution. Lists just the names, no inode data, alphabetical, not case sensitive, formatted into columns. Although it's row-major instead of column major like the default output of ls. The columns get a little messy if there is a file name with >26 characters.

rm -f /tmp/lsout
ls -1p | grep / | sort -f >> /tmp/lsout
ls -1p | grep -v / | sort -f >> /tmp/lsout

IFS=$'\n' read -d '' -r -a lines < /tmp/lsout

printf "%-24s  %-24s  %-24s\n" "${lines[@]}"

And another, with some extra formatting.

rm -f /tmp/lsout
echo "  ---- Directories ---- " >> /tmp/lsout
ls -1p | grep / | sort -f >> /tmp/lsout
IFS=$'\n' read -d '' -r -a lines < /tmp/lsout
printf "%-24s  %-24s  %-24s\n" "${lines[@]}"

rm -f /tmp/lsout
echo "  ------- Files ------- " >> /tmp/lsout
ls -1p | grep -v / | sort -f >> /tmp/lsout
IFS=$'\n' read -d '' -r -a lines < /tmp/lsout
printf "%-24s  %-24s  %-24s\n" "${lines[@]}"

Output for the last one looks like the following, minus the colors:

  ---- Directories ----   archive/                  bookmarks/              
Desktop/                  Documents/                Downloads/              
fff/                      health/                   Library/                
Movies/                   Music/                    Pictures/               
Public/                   rrf/                      scifi/            
testdir/                  testdir2/                                         
  ------- Files -------   @todo                     comedy            
delme                     lll                       maxims                  
schedule                  vtokens style

Just remember not to alias or change the default behavior of ls since this script calls it.

share|improve this answer

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

Long options:

ls
    -l    # List
    --all
    -X    # Sort alphabetically by entry extension
share|improve this answer
    
This would only work if you could be absolutely certain that every directory had no dots in its name. – eleven81 Feb 16 '10 at 13:43

Another way ...

find . -d 1 -type d | ls -la | sort -r 

OR

ls -la | sort -r

OR

d=`find . -type d -d 1`;f=`find . -type f -d 1`; echo -e -DIRS- "\n$d\n" -FILES- "\n$f"
share|improve this answer
    
What do these do? Where did you learn to type them? – Tom Wijsman Jun 11 '12 at 18:31
    
Well My preferred OS is Debian Linux. Debian's gnu core utils package version of ls supports the --show-directories-first option ... when I started using OSX I simply grabbed my all my bash dot files from my Debian box and dropped them in my home directory ... I had a lot of bash_aliases that broke so ... It was then that I had to figure out some work-arounds for my aliases ... – Eddie B Jun 12 '12 at 1:13
    
The first one is a bit redundant ... There's really no reason to sort for the directories as it's the order we need to modify not directories ... the 'ls -la | sort -r' is what really works. Basically it's stating ... 1) A) Find . -d 1 -type d (Start from this directory, search one directory depth and search for directories only) B) ls -la (list files all attributes) C) Sort them in reverse 2) Do as 1) just drop the find ... it's not needed ... I actually like Studers' solution better ... :-) – Eddie B Jun 12 '12 at 1:21

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:

.
..
DIR
Dir
dir
.hidden
123
UC_FILE
Uc_file
lc_file

Although, if I recall correctly, the hidden dot files originally appeared before the directories.

share|improve this answer

You've got several choices, depending if you want to keep alphabetical order.

You could simply try :

ls -al | sort -k1 -r

or this, to keep alphabetic order for files with the same permissions :

ls -al | sort -k1,1 -k9,9 -r

or, as eleven81 said (but this version lists everything) :

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

share|improve this answer
1  
This is a nicer solution IMO. Using several processes and pipes to do sorting instead of piping to sort seems kind of backwards. Especially since ls- al|sort -k1 -r works. What was missing is just the -r flag. – brice Feb 17 '10 at 13:54
    
@brice The thing that bothers me about 'sort' is that ./ and ../ won't be the first two lines, in that order. Other than that, I agree that it's the more efficient solution. – 10basetom Oct 23 '15 at 21:41

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';
}
share|improve this answer
    
Just an fyi this doesn't appear to work. You need to use long listing format (ls -l) in order to filter by file type like that. Also, this command will break on spaces (in bash). You need to quote like so: "$@" If you want to use this approach, you could do something like so: function lss {local temp="$(command ls -l --color=always "$@")"; egrep --color=never '^d|total' <<<"$temp"; egrep --color=never -v '^d|total' <<<"$temp"} – Six Jul 24 '15 at 0:29

protected by JakeGould Oct 24 '15 at 20:09

Thank you for your interest in this question. Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site.

Would you like to answer one of these unanswered questions instead?

Not the answer you're looking for? Browse other questions tagged or ask your own question.