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.
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
Try doing this using bash builtins (display an integer like the KB version)
var="120928312 http://blah.com"
echo "$(( ${var%% *} / 1024)) MB"
how about this line:
kent$ echo "120928312 http://blah.com"|awk '{$1/=1024;printf "%.2fMB\n",$1}'
118094.05MB
function bytes_for_humans {
local -i bytes=$1;
if [[ $bytes -lt 1024 ]]; then
echo "${bytes}B"
elif [[ $bytes -lt 1048576 ]]; then
echo "$(( (bytes + 1023)/1024 ))KiB"
else
echo "$(( (bytes + 1048575)/1048576 ))MiB"
fi
}
$ bytes_for_humans 1
1 Bytes
$ bytes_for_humans 1024
1KiB
$ bytes_for_humans 16777216
16MiB
Try using awk
awk '{MB=$1/1024; print $MB}'
$1
- value of the first column, size (KB) in this case