Dired: human-readable sizes and sort by size

We’ve looked a few times at dired, emacs’ powerful file browser. This time I want to look at file sizes in dired. By default, dired lists file sizes in bytes, but this is easy to change by customising the switches that dired uses when it calls your system’s ls command to generate the directory listing.

Add the following to your emacs config file to have file sizes given in “human-readable” format (i.e. in units of B, K, M, G as appropriate).

;; dired                                                                  ;;
(setq dired-listing-switches "-alh")

We already saw that hitting s in a dired window changes the sorting between file name and modification date. It is also nice to sort by file size sometimes. To do this, we can use the prefix argument in front of the s command, so use C-u s in the dired buffer. This prompts us for the ls switches, which we can change from -alh to -alhS to sort by size. Xah Lee covers this in more detail in his extensive emacs pages.

  • Is there a way to see the effect of dired-listing-switches without restarting emacs? I evaluated the expression, but dired didn’t use it until I restarted emacs.

    • Ben Maughan

      Not that I know of. You can use C-u s in a dired buffer, but that only changes the switches for that instance of dired. If you run another dired command you get the default switches back.

    • Nick Roosevelt

      You can set the region to be that line, then do `M-x eval-region` and it will take effect immediately, but you need to kill the dired buffer and re-open it.

  • Be careful that the `ls` command behaves differently on different os. For Mac, some arguments are different and some cannot be understood. To fix that, you can install the GNU Coreutils (collection of commands like ls, cat,…) used on GNU/Linux.
    I wrote an instruction here for Mac users (since I use Mac, too) https://truongtx.me/2013/04/25/dired-as-default-file-manager-5-customize-ls-command/