Skip to content

du -sh to du -sk

May 12, 2005

This mornings wake up problem in the email was this. Given a file that contains the output of “du -sh” for a number of files how can you sort the output based on the size of the files.

Simplest solution is to not use “du -sh” but use “du -sk” and then pipe it to sort(1). However this du could take a while to run so it might just be quicker to use this nawk script (sadly I typed this straight in):

nawk ‘{         if ($1 ~ ".*G") {                 sub("G", "", $1); $1*=1024*1024         } else {                 if ($1 ~ ".*M") {                         sub("M", "", $1); $1*=1024                 } else {                         if ($1 ~ ".*K") {                                 sub("K", "", $1)                         }                 }         }         printf("%dK %s\n", $1, $2) }’  /var/tmp/input_file | sort -n 

Which takes this:

 1.1G   /export/home/.dh/user1  1.1G   /export/home/.dh/user2    4K   /export/home/.dh/user3  4.0G   /export/home/.dh/user4  7.7G   /export/home/.dh/user5   12K   /export/home/.dh/user6   12K   /export/home/.dh/user7   48M   /export/home/.dh/user8  102M   /export/home/.dh/user9  130M   /export/home/.dh/user10  519M   /export/home/.dh/user11 

And gives you this:

4K /export/home/.dh/user3 12K /export/home/.dh/user6 12K /export/home/.dh/user7 49152K /export/home/.dh/user8 104448K /export/home/.dh/user9 133120K /export/home/.dh/user10 531456K /export/home/.dh/user11 1153433K /export/home/.dh/user1 1153433K /export/home/.dh/user2 4194304K /export/home/.dh/user4 8074035K /export/home/.dh/user5 

I leave the conversion back into human readable form as an exercise for the reader.

Tag: , awk


From → Solaris

Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: