Monday, November 1, 2021

[SOLVED] Show DU outcome in purely megabytes

Issue

I am using DU function to output the directory size to a file and then move it to an excel file to add the total. Is it possible to output the size of a directory only in MB (even if the size is in KB or GB):

e.g. if the file size is 50kb the output would show 0.048MB

I'm aware of du -h however I haven't been able to maintain the size in MBs if the size is larger than 1024, since it's switches to 1G. The du -m however does not show the M (for megabytes) next to the value so isn't really human friendly.

Thanks in advance, J


Solution

It's the -m option. So, for example:

$ du -s -m <my_directory_here>

UPDATE

Oh... you want an "M" printed after the number of megabytes. Here you are:

$ du -s -m /usr/local | sed 's/^\([0-9]*\)\(.*\)$/\1M \2/'

or...

$ du -s -m /usr/local | sed 's/^\([0-9]*\)\(.*\)$/\1MiB \2/'

or...

$ du -s -m /usr/local | sed 's/^\([0-9]*\)\(.*\)$/\1 MegaBytes \2/'

etc.

UPDATE2

If you want fractions I would use du -k to print KiB and then:

$ du -s -k * | awk '{printf "%.3f MiB %s\n", $1/1024, $2}'
43.355 MiB bin
0.008 MiB etc
0.562 MiB include
5.836 MiB lib
0.008 MiB man
0.004 MiB mysql
2259.738 MiB mysql-5.5.27-osx10.6-x86_64
45.711 MiB share
340.641 MiB texlive


Answered By - mauro