Making Sense of The Infinite

Unlocking Infinite Possibilities Through Curiosity

How to Sort Files by Size in Multilevel Directories in Linux / macOS

Managing files on Linux often involves identifying the largest files within a directory and its subdirectories, particularly when disk space is at a premium. This article explains how to search for files in Linux and sort them by size, with the largest files appearing first. We’ll explore a few efficient command-line methods to achieve this.

Using find and ls for Detailed File Information

The find command, combined with ls, is a powerful way to locate files and display their sizes in human-readable format. To search through a directory and its subdirectories while sorting files by size, use the following command:

find /path/to/directory -type f -exec ls -lh {} + | sort -k 5 -rh
ShellScript

Explanation of the Command:

  1. find /path/to/directory -type f:
    • This searches for all files (not directories) in the specified path.
  2. -exec ls -lh {} +:
    • This lists the files in a human-readable format (-lh) showing file sizes.
  3. sort -k 5 -rh:
    • The -k 5 option sorts by the fifth column, which is the file size in the ls -lh output.
    • The -r flag ensures the sorting is in descending order, with the largest files displayed first.
    • The -h option enables human-readable size sorting (e.g., K, M, G).

Using find and du for a Simpler Output

If you prefer a cleaner output that focuses solely on file size and path, the following command is more appropriate:

find /path/to/directory -type f -exec du -h {} + | sort -rh
ShellScript

Here’s what this command does:

  1. The find command works similarly to the previous example, locating all files in the specified directory.
  2. du -h calculates the disk usage of each file and outputs it in a human-readable format.
  3. sort -rh arranges the files in descending order by size.

Example Output:

2.0G /home/user/documents/large_file.iso
500M /home/user/documents/video.mp4
300K /home/user/documents/small_file.txt

Practical Use Cases

These commands are particularly useful in scenarios like:

  • Identifying large files that are consuming disk space.
  • Cleaning up old or unnecessary files.
  • Diagnosing disk space issues on Linux servers.

For example, running these commands in /var/log can help locate oversized log files that might be bloating your server’s storage.

Sorting files by size on Linux is straightforward using the find command in combination with either ls or du. Depending on your needs, you can choose between a detailed view with file permissions and timestamps or a simpler output focused on size and path. These methods are invaluable for system administrators and power users seeking to optimize disk usage.

Last revised on

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *