Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert KB To MB using Bash

Tags:

bash

shell

I use a command to get the size of a remote folder, after it's run it returns

120928312 http://blah.com

The number is size in bytes. What I'd like to do is have it output in MB, and the http part removed. I'm guessing greping to a file but not sure how to go about it.

like image 371
Lurch Avatar asked Sep 27 '13 20:09

Lurch


2 Answers

You can do it with shell builtins

some_command | while read KB dummy;do echo $((KB/1024))MB;done

Here is a more useful version:

#!/bin/sh
human_print(){
while read B dummy; do
  [ $B -lt 1024 ] && echo ${B} bytes && break
  KB=$(((B+512)/1024))
  [ $KB -lt 1024 ] && echo ${KB} kilobytes && break
  MB=$(((KB+512)/1024))
  [ $MB -lt 1024 ] && echo ${MB} megabytes && break
  GB=$(((MB+512)/1024))
  [ $GB -lt 1024 ] && echo ${GB} gigabytes && break
  echo $(((GB+512)/1024)) terabytes
done
}

echo 120928312 http://blah.com | human_print
like image 154
technosaurus Avatar answered Oct 21 '22 19:10

technosaurus


How about this line:

$ echo "120928312 http://blah.com" | awk '{$1/=1024;printf "%.2fMB\n",$1}'
118094.05MB
like image 41
Kent Avatar answered Oct 21 '22 20:10

Kent