Emacs: Sort File by Time, Size, in Dired

By Xah Lee. Date: . Last updated: .

Here's a emacs command that lets you sort dired file listing by any {date/time, size, name, dir}.

(defun xah-dired-sort ()
  "Sort dired dir listing in different ways.
Prompt for a choice.
URL `http://ergoemacs.org/emacs/dired_sort.html'
Version 2015-07-30"
  (let (-sort-by -arg)
    (setq -sort-by (ido-completing-read "Sort by:" '( "date" "size" "name" "dir")))
     ((equal -sort-by "name") (setq -arg "-Al --si --time-style long-iso "))
     ((equal -sort-by "date") (setq -arg "-Al --si --time-style long-iso -t"))
     ((equal -sort-by "size") (setq -arg "-Al --si --time-style long-iso -S"))
     ((equal -sort-by "dir") (setq -arg "-Al --si --time-style long-iso --group-directories-first"))
     (t (error "logic error 09535" )))
    (dired-sort-other -arg )))

Just put the above in your emacs init. You can give it a keybinding for easy call. 〔➤see Emacs: How to Define Keys

Note: this may not work in Mac OS X. You need to have GNU's version of ls.

The following is how to do it in plain emacs.

How sort file by size in dired?

In dired, type 【Ctrl+u s】, then in prompt, modify it to be -alS.

The command is dired-sort-toggle-or-edits】.

Here's some common ls options for sort:

emacs dired sort 2014-09-25
emacs dired customized listing. (the coloring is from Dired Plus Mode)

also, dired by default list the current directory . and parent directory ... You can disable that. Put this in your emacs init:

(setq dired-listing-switches "-Al --si --time-style long-iso")

the --si option displays file size in metric prifex of k (1000), m (1000k), etc.

the --time-style long-iso option displays date in the format “yyyy-mm-dd”.


-rw-rw-r-- 1 xah xah 9.2k 2014-09-22 20:21 dired_sort.html

in dired, when you type 【s】, the command called is dired-sort-toggle-or-edit.

Dired topics

Like it? Buy Xah Emacs Tutorial. Thanks.

or, buy something from Best Keyboard for Emacs