Wednesday, January 7, 2009

Sort files and directories by size - Linux bash


In my current directory, I have the following files/sub-directories:

$ file *
conf: directory
main.dat: ASCII text
temp.txt: ASCII text
tmplog: 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 +0nr
4260 tmplog
2980 conf
1100 main.dat
968 temp.txt

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

$ du --max-depth=1 . | sort -nr
9308 .
4260 ./tmplog
2980 ./conf


Since the sub-directories also contains files; lets list all the files (not directories) in the descending order of file sizes

$ find . -type f -exec du -sk {} \; | sort -nr
2196 ./tmplog/main1.dat
2064 ./conf/pi.dat
1100 ./tmplog/huo.txt
1100 ./main.dat
968 ./temp.txt
964 ./tmplog/as.txt
916 ./conf/lis.txt

And if you want to restrict find to the current directory only and not the sub-directories, use maxdepth=1. i.e.

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

No comments:

© Jadu Saikia www.UNIXCL.com