Sum up files whose size Kbytes and Mbytes

Hello Friends,

When i type

du -sh *.jar | sort -n

under a library directory i get a result similar below output:

   1M    1.jar
2.4M     2.jar
4.5M     3.jar
     .      .
     .      .
     .      .
    1K   (n-2).jar
  15K    (n-1).jar
77.7K     n.jar

I want to sum up the size of all files in terms of Kbytes or bytes, i wrote this code, but im not sure if this is the optimum way to do it with awk:confused:, i need your modification or comments.

du -sh *.jar |nawk '{sub("K$","",$1); a+=$1}{sub("M$","",$1); b+=$1*1000}END{printf "%12d\n",s=a+b}'

First, you'll be getting a wrong result, as the GNU version of df (the only I know that supports the '-h' switch) uses the binary correct 1024 (=2^10) as the multiplicand, not 1000.

Second, if you want KiB, why not use the appropriate switch, and then sum it:

du -ks *.jar | sort -n | awk '{print; total+=$1;}END{print total}'

It's even portable