Commands.page Logo

How to Sort Directory Listing by File Size in Ubuntu

Managing disk space and organizing files in Ubuntu often requires identifying which items consume the most storage. This article provides a concise guide on using the terminal to sort directory listings by file size, allowing you to quickly locate large files without needing graphical interface tools.

Using the ls Command

The primary method to view and sort files is using the ls command in the terminal. To see file sizes alongside names, you must use the long listing format. Combine this with the sort flag to organize the output based on size.

Sort by Largest to Smallest

To list files with the largest at the top, use the -S flag along with -l for detailed information. Run the following command in your terminal:

ls -lS

This displays files in descending order. Adding the -h flag makes the sizes human-readable (e.g., KB, MB, GB) instead of showing bytes:

ls -lhS

Sort by Smallest to Largest

If you need to see the smallest files first, add the -r flag to reverse the order. This is useful for finding small configuration files or logs amidst larger data:

ls -lSr

You can also combine this with the human-readable flag:

ls -lhSr

Sorting Hidden Files

By default, these commands do not show hidden files that start with a dot. To include hidden files in your size-sorted list, add the -a flag:

ls -lahS

This comprehensive command lists all files, including hidden ones, in long format with human-readable sizes, sorted from largest to smallest.