How to convert Kilobytes to Megabytes or gigabytes through terminal?
The shell does fixed-width integer arithmetic with no check for overflow. So, when doing a calculation that might involve either large numbers or fractions, bc
is a good choice. To get megabytes:
$ echo "scale=2; $(sudo fdisk -s /dev/sda6) / 1024" | bc
13641.75
To get gigabytes:
$ echo "scale=2; $(sudo fdisk -s /dev/sda6) / 1024^2" | bc
12.70
The assignment scale=2
tells bc
to display two decimal places.
numfmt
(part of GNU Coreutils) can be used here:
$ sudo fdisk -s /dev/sda | numfmt --to=iec-i --suffix=B --format="%.2f"
931.52MiB
In awk
To find the size of the disk in Megabytes,
$ sudo fdisk -s /dev/sda | awk '{$1=$1/1024; print $1,"MB";}'
953870 MB
To find the size of the disk in Gigabytes,
$ sudo fdisk -s /dev/sda | awk '{$1=$1/(1024^2); print $1,"GB";}'
931.513 GB