Shell Programming Blog Shell Programming Blog

Saturday, 29 September 2012

How to sort the files and directories based on their size

Unknown | 23:25 | | | Be the first to comment!




Let us see how to sort the files and directories. In my current directory, I have the following files and sub-directories:

$ file *
config: directory
val.dat: ASCII text
sample.txt: ASCII text
log: directory

i.e., 2 files and 2 directories

Now to list the files and directories (in the current directory) in the descending order of file size.

$ du -sk * | sort -nr
4730 log
2779 config
1100 val.dat
968 sample.txt

To list only the directories (in the current directory) in descending order of size:

$ du --max-depth=1 . | sort -nr
9308 .
4730 ./log
2779 ./config


Since the sub-directories also contain files, let's list all the files (not directories) in the descending order of file sizes

$ find . -type f -exec du -sk {} \; | sort -nr
2196 ./log/main1.dat
2064 ./config/pi.dat
1100 ./log/huo.txt
1100 ./val.dat
968 ./sample.txt
964 ./log/as.txt
916 ./config/lis.txt


If you would like to restrict find to the current directory only and not the sub-directories, use need to use maxdepth=1. i.e.

$ find . -maxdepth 1 -type f -exec du -sk {} \; | sort -nr
1100 ./val.dat
968 ./sample.txt

 

Shell Programming Copyright © 2012 Shell Programming theme is Designed by Abusittik, Shell Programming