5

How can I output all files/directories, ordered by size, including hidden ones
(those whose name starts with a dot), all in one go?

By size of a directory, I mean the sum of all file sizes in the directory and all of its subdirectory tree.

The difference to How can I sort the output of du -h by size? is that I'm requesting an output that includes all files and directories in the current directory – whether hidden or not.

References

1 Answer 1

16

How can I output all files/directories, ordered by size, including hidden ones?

Use the du (disk usage) command, which is part of GNU coreutils : 1

du -hs -- * .[^.]* | sort -h

The .[^.]* regular expression ensures that hidden files and directories are included.

To list only hidden files and directories, sorted increasing in size :

du -hs -- .[^.]* | sort -h

List only directories – whether hidden or not – sorted increasing in size :

du -hs -- */ .[^.]*/ | sort -h

List only files in the current directory

List all files, sorted increasing in size : 2

ls -AhlS | grep '^-' | tac

List only hidden files, sorted increasing in size :

ls -hldS .* | grep '^-' | tac

List only regular (non-hidden) files, sorted increasing in size :

ls -lS | grep '^-' | tac

List files recursively – in all of the subdirectory tree

This isn't asked about in the question, but sometimes you may want to list all files in the subdirectory tree (including the current directory), ordered by size. 3

du -ah | sort -h

The output will be a list (possibly dauntingly long) of both subdirectories and files. To restrict it to files only, you'll need to have an idea of what file extension the largest files have (by looking at the output from the above command).

du -ah | sort -h | grep .<file-extension>

Here you should replace <file-extension> with zip, png, jpg, or whatever file extension the largest files have.

Examples:

du -ah | sort -h | grep .zip
du -ah | sort -h | grep .png

References


1 I gratefully attribute my solution to this comment. The -- argument marks the end of options.
The du command can be painfully slow for very large files/folders. Consider using the ncdu command instead.
To install on a Debian derivative, including Ubuntu, run: sudo apt install -y ncdu.
On Arch Linux, including MSYS2, run: yes | pacman -Syu ncdu.
To use it, type ncdu, and press .

2 The -h flag of ls outputs the file sizes in a human-readable style.
The -S flag sorts the output in the order of decreasing size.
The pipe | grep '^-' excludes directories and symbolic links.
The pipe | tac reverses the output.

3 This is more likely to be of interest when the size of the current directory is a few megabytes rather than gigabytes.

You must log in to answer this question.

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