Sort all file sizes in a directory in Linux

We can use multiple commands like ls, du to sort all the files by size in a directory of Linux system. The trick here is to pass some additional arguments along with ls and du commands. Let us see below what are the arguments that should be passed to sort files by size in a Linux directory

Sorting by ls command

The most basic ls command will allow us to sort by the file sizes but it has some disadvantages

##Basic ls command to sort by file sizes
ls -S

##Where l is for long listing format, h is for human  and Size is to sort by size
ls -lhS

##If you want to exclude directories, then you can use the below command
ls -lhS | grep -v '^d'

##The below one will also work (This sorts the file by 5th column which has size)
ls -lh | sort -k 5hr

##To properly handle all sparse files
ls -lsh | sort -n | sed 's/^[0-9 ]* //'

Sorting by du command:

The other way to sort the file by it’s size is to use the “du” command and then sort it by sort command

#This will print all the files and sort it
du -ha | sort -h

#Another way
du -h | sort -rh

#Another way
du -ah | sort -hr


You may also like...