ls sort by size in linux/unix

In Linux, to sort files by size using the ls command, you can use the -S option, which sorts the output by file size, largest first. Here are some examples:

  1. Sort by size in ascending order (largest files last):
   ls -S
  1. Combine with long format listing to show detailed information about files:
   ls -lS
ls sort by size
  1. Sort by size in descending order (smallest files first) by adding the -r option:
   ls -lSr
  1. Sort by size, but only show files, not directories:
   ls -lS | grep -v '^d'
  1. Sort by size and show only the top 5 largest files:
   ls -lS | head -n 5
  1. Sort by size and show only the bottom 5 smallest files:
   ls -lS | tail -n +6
  1. Recursively sort all files in a directory and its subdirectories by size:
   ls -lR -S | grep ':$'

The ls -S command is particularly useful when you want to quickly identify the largest files in a directory, which can be helpful for managing disk space. Remember that the sorting is done based on the apparent size of the files, which for regular files is the actual disk usage, and for directories, is the sum of the sizes of the files within them.

This entry was posted in File & Directory, Ls Command and tagged , , , . Bookmark the permalink.