Search code examples
bashshellawksolarisksh

How to show only total file size of particular extension in MB GB OR KB in solaris KSH Shell script


How to show only total file size of particular extension in MB GB OR KB in sun solaris KSH Shell script I have tried AWK command, below is command:-

BACKUP_SIZE=`find $EXPDP_DIR_PATH -name "DotNet_LI_TRADES_pre_release_*_12092017.log" -exec ls -ltr {} \; | awk ' BEGIN{split("B KB MB GB TB PB EB ZB YB",v)} {s+=$5} {s=1;while($5>1024&&s<9){$5/=1024;s++}  printf "%6.2f %s\n",$5,v[s],$9}'`

Output:-

echo $BACKUP_SIZE

681.02 MB 682.54 MB 552.33 MB 1.77 GB 5.92 GB 374.07 MB

Desired Output:-

66.87 GB

Solution

  • I believe your output should be around 9.9 GB seems to be typo. If your Input_file is same as shown sample then following may help you in same too.

    BACKUP_SIZE="681.02 MB 682.54 MB 552.33 MB 1.77 GB 5.92 GB 374.07 MB"
    echo $BACKUP_SIZE | 
      nawk '{
        for (i=2;i<=NF;i+=2) {
          if ($i=="MB") {
            val=val?val+$(i-1)*.001 : $(i-1)*.001
          } else {
            val=val?val+$(i-1) : $(i-1)
          }
        }
      }
      END { print val }' 
    

    Since you have added Solaris on this question so adding here: on a Solaris/SunOS system, change awk to /usr/xpg4/bin/awk , /usr/xpg6/bin/awk, or nawk

    EDIT: As OP needs to get answer in 2 floating point so following may help you in same.

    echo $BACKUP_SIZE |
      nawk '{
        for(i=2;i<=NF;i+=2) {
          if ($i=="MB") {
            val=val?val+$(i-1)*.001 : $(i-1)*.001
          } else {
            val=val?val+$(i-1) : $(i-1)
          }
        }
      }
      END { 
        printf("%.02f %s\n", val, "GB" )
      }'