I have a widget on my desktop which shows the current size of the files in my 'Trash'. The code for the widget is the following:du -ch ~/.Trash | grep total | cut -c 1-5This will give me something like: '99M'. But I would like to display '99 MB' instead (and KB, GB respectively). Could you help me to replace the code with the right string to get this result (also notice the space between '99' and 'MB')? Thanks in advance!PS: I use Mac OS X 10.11.6.
How to print human readable format in KB, MB, GB instead of K, M, G?
bash
I find that, when the size is between 10K and 99K (say, for example, 42K),the first five characters of the output are42K(tab)/(assuming that the pathname argument begins with / which it will, if youre specifying anargument that begins with ~).So that will be the output of cut-c1-5: 42K/.(Ipresume that nnM and nnGwill have the same problem.)It makes more sense to use cut-f1 to get the first field of the output,rather than the first five characters.What happens if you have a directory name that includes the word total?Hint: Itll get through the grep.Rather than have df generate the data for every subdirectory,and then have grep throw it away,it makes more sense to have df generate only the total.As RomanPerekhrest points out,you can do that by specifying the -s option.As dmgnx points out,once youve got the number (ending with K, M or G),all you need to do is append the B.So my composite solution isecho $(du -sh ~/.Trash | cut -f1)BOops! I didnt noticethat you wanted to add a space between the number and the units.OK, then you do need sed (or something similar):du -sh ~/.Trash | cut -f1 | sed 's/[KMG]$/ &B/'or perhaps justdu -sh ~/.Trash | sed 's/^\([0-9.]*\)\([KMG]\).*$/\1 \2B/'(using sed to discard the directory name,and eliminating the cut altogether).