5 Ways To Use ls Command to Sort Files by Size in Linux

TL;DR

To use the ls command to sort files by size in Linux, you can try any of these five methods:

  1. Use ls -lS to list files from largest to smallest, making it easy to spot and manage the biggest space hogs.
  2. Execute ls -lSr to see the smallest files first, helping you clean up minor files or quickly access smaller documents.
  3. With ls -laS, you can sort all files, including hidden ones, by size, ensuring a comprehensive cleanup.
  4. ls -lhS sorts files by size and displays sizes in a user-friendly format (KB, MB, GB), aiding in easier file management decisions.
  5. Using ls -lS | head -n N highlights the top N largest files, ideal for quick space-saving actions.

The ls command in Linux supports advanced file sorting techniques, enhancing directory management through precision control with awk and sort, recursive and human-readable size sorting, focused sorting by file type using grep, efficiency via custom aliases, and multi-dimensional sorting by size and time. These strategies enable detailed analysis, streamlined workflow, and effective storage management, catering to specific needs like report generation, data organization, and prioritization for backup or deletion.

Read the guide below to learn more about using the the ls command to sort files by size and some advanced practices for using the ls command for sorting.

Managing a cluttered folder on your Linux system can feel like navigating a maze without a map. Luckily, there’s a neat trick to see your files and organize them by size quickly. This post is all about mastering the ls command to sort your files by size, making it super easy to identify and manage large files, clean up your space, and get your file organization on point. From basic sorting to digging into hidden files and even customizing how you view file sizes, I’ve laid out five straightforward methods to get your files lined up just the way you need.

What Is ls Command In Linux?

The ls command in Linux is a utility used to list the contents of directories. It provides a way to view information about files and directories in the file system, including file names, permissions, ownership, and file size. The ls command can be used with various options to customize the output, such as -l for detailed listings, -a to include hidden files, and -h to display file sizes in a human-readable format. This command is fundamental for navigating and managing files in a Linux environment, offering users a quick overview of directory contents.

How to Use ls Command to Sort Files by Size in Linux?

To use the ls command to sort files by size in Linux, you can employ the -l option combined with the -S option. The -l option provides a detailed listing of files and directories, while the -S option sorts them by size in descending order, meaning the largest files appear first. If you want the smallest files to appear first, you can additionally use the -r option to reverse the sort order. Here’s how you would use the command:

ls -lS  # Lists files sorted by size, largest first
ls -lSr # Lists files sorted by size, smallest first

This command will display the files with details such as permissions, number of links, owner, group, size, and time of last modification, alongside the file names.

5 Ways To Use The ls Command In Linux To Sort Files

1. Basic Sorting by Size

This method lists files from largest to smallest, making it easy to see which files take up the most space. It’s great for quickly identifying large files that you might want to delete or compress to save space. Follow these steps:

  1. Launch your terminal application to get started.
opening-terminal
  1. Navigate to the directory you want to sort by running the following command:
<strong>cd /path/to/directory</strong>

Replace /path/to/directory with the directory you want to sort.

navigating to directory
  1. Type the following command and press Enter. 
<strong>ls -lS</strong>

Your files will be listed in descending order by size, with the largest files at the top.

sorting files in descending order by size

2. Reverse Sorting by Size

Reverse sorting shows you the smallest files at the top. This can help you tidy up small, unnecessary files cluttering your directory or find small scripts and documents faster among larger files. Here is the step-by-step guide:

  1. Access your terminal through your Linux distribution’s interface and go to the directory you’re interested in.
  2. Run the following command:
<strong>ls -lSr</strong>

Files will appear in ascending order by size, showing the smallest files first.

sorting files in ascending order by size

3. Including Hidden Files in the Sort

Sorting with hidden files included gives you a full picture of everything in your directory, even files that are normally out of sight. This is helpful for a thorough cleanup or when checking for concealed files. To include hidden files while sorting, follow these steps:

  1. Open your terminal window from the desktop or application menu and access the directory you want to sort.
  2. Execute the command: 
<strong>ls -laS</strong>

All files, including hidden ones, will be sorted by size in descending order.

sorting hidden files in descending order by size

4. Human-Readable Sizes with Sorting

By sorting files and showing their sizes in a format that’s easy to understand (like KB, MB, GB), this method makes it simpler to decide which files to manage, share, or remove. Here are the steps to follow:

  1. Access the Terminal application on your system and navigate to the directory of interest.
  2. Type the following command and press Enter:
<strong>ls -lhS</strong>

Files will be listed with human-readable sizes, sorted by size.

sorting with human readable sizes

5. Sorting and Displaying the Top N Largest Files

This method quickly highlights the top N largest files, directly showing you the main culprits of used space. It’s ideal for when you need to free up space fast by dealing with the biggest files first. Here is the step-by-step guide:

  1. Open the Command prompt from your applications menu and move to the directory.
  2. Run the following command: 
<strong>ls -lS | head -n N</strong>

Replace N with the number of files you want to see. The top N largest files will be displayed.

sorting top most space consuming files

Advanced File Sorting Techniques in Linux with ls Command

The ls command in Linux is versatile, offering various ways to sort files by size for better directory management. Here are five advanced techniques, each designed to enhance your file sorting process, from precision control to comprehensive directory analysis:

  • 🛠 Precision Sorting with awk and sort: Tailor your file listings with precise control by combining the awk and sort commands. This approach lets you extract and focus on specific file attributes, such as size or name, sorting them according to your precise requirements. It’s particularly useful for generating reports or audits where detailed file information is critical. To execute this level of detailed sorting, use the command: ls -l | awk '{print $5, $9}' | sort -n.
  • 📁 Recursive Sorting with Human-Readable Sizes: Explore every corner of your filesystem with a recursive sorting strategy that brings to light the files taking up space, even in the least visited subdirectories. By using find with ls -lh, you can list files in a human-readable format and then sort these results by size. This technique is indispensable for comprehensive storage management and cleanup processes. Implement this recursive sorting with: find . -type f -exec ls -lh {} + | sort -hrk 5.
  • 🔍 Filtered Sorting by File Type with grep: Concentrate your sorting efforts on particular file types or patterns by integrating grep with your ls command. This selective sorting helps quickly locate and organize specific groups of files, making it a vital technique for managing large collections of data or documents. For a focused sort on .txt files, the command is: ls -lh | grep '.txt' | sort -h.
  • Custom Aliases for Sorting Commands: Enhance productivity and streamline your command-line workflow by creating custom aliases for your most-used sorting commands. This technique reduces the complexity and length of frequent commands to simple, memorable shortcuts, optimizing your time and effort on the terminal. Set up an alias for sorting files by size with: alias lssize='ls -lS'.
  • 🕒 Multi-Dimensional Sorting by Size and Time: Sort your files not just by their size but also by their modification times with a multi-dimensional sorting approach. This method sorts files by size and then further sorts them by their last modified time, offering a layered perspective on your data. It’s particularly useful for prioritizing files for backup or deletion. For multi-dimensional sorting, you might use a combination like: ls -lS | sort -k 6,7.

Final Thoughts

I really hope you found this guide on sorting files by size with the ls command helpful. I’ve gone through many steps, from the basics to including those sneaky hidden files and making file sizes easier to understand. It’s all about making your life a bit easier when dealing with many files in Linux. Along the way, I’ve also covered how to troubleshoot common errors and adopt best practices for file management.

If you’re curious to learn even more, there’s plenty more cool stuff out there. You can learn how to pinpoint specific file types with grep, navigate directories like a pro with the find command, or automate tasks with bash scripts. Each skill you add makes your Linux journey more exciting and turns you into a more adept user, ready to tackle any file management challenge.

Frequently Asked Questions

  1. Can I sort files by modification date using ls?

    Yes, use the command ls -lt to sort files by modification date, displaying them in descending order of their last modification time. This command efficiently organizes files based on when they were last edited.

  2. How do I view the total size of all files in a directory?

    To find the total size of all files in a directory, utilize du -sh. This command summarizes (‘-s’) the space files take and presents it in a human-readable (‘-h’) format, showing the total size.

  3. How do I exclude directories when listing files by size?

    To list files by size, excluding directories, use find . -maxdepth 1 -type f -exec ls -lhS {} +. This command lists files in the current directory without entering subdirectories, sorting them by size.

  4. What command can I use to sort directories only, ignoring files?

    For sorting only directories by size, the command du -sh */ | sort -h is useful. It displays directories with their sizes and sorts them in a human-readable format, focusing solely on directory sizes.

  5. Can I use ls to sort files by size across all subdirectories?

    While ls does not directly support sorting files by size across subdirectories, combining find, ls, and sort as in find . -type f -exec ls -lhS {} + | sort -hrk 5 achieves a recursive size sort.

Ojash

Author

Ojash is a skilled Linux expert and tech writer with over a decade of experience. He has extensive knowledge of Linux's file system, command-line interface, and software installations. Ojash is also an expert in shell scripting and automation, with experience in Bash, Python, and Perl. He has published numerous articles on Linux in various online publications, making him a valuable resource for both seasoned Linux users and beginners. Ojash is also an active member of the Linux community and participates in Linux forums.

Akshat

Reviewer

Akshat is a software engineer, product designer and the co-founder of Scrutify. He's an experienced Linux professional and the senior editor of this blog. He is also an open-source contributor to many projects on Github and has written several technical guides on Linux. Apart from that, he’s also actively sharing his ideas and tutorials on Medium and Attirer. As the editor of this blog, Akshat brings his wealth of knowledge and experience to provide readers with valuable insights and advice on a wide range of Linux-related topics.

Share this article
Shareable URL
Prev Post

3 Best Methods to Replace a Substring With Another String in Bash

Next Post

How to Use Tar Command in Linux [16 Best Uses]

Leave a Reply

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

Read next