du -sh to du -sk

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

Comments:

Post a Comment:
Comments are closed for this entry.
About

This is the old blog of Chris Gerhard. It has mostly moved to http://chrisgerhard.wordpress.com

Search

Archives
« April 2014
MonTueWedThuFriSatSun
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
    
       
Today