Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bash du with byte size in decimals to the nearest thousandth

Tags:

bash

Is it possible in BASH to do a "du" command with the byte size shown in decimals.

For example, say I have the following files (numbers are in bytes):

12345 file1
2345 file2
6491 file3

I would like to do a "du" command in linux that would output the following instead:

12.3 file1
2.3 file2
6.5 file3

Note: The "-h" flag does not work.

like image 886
James Nine Avatar asked Jan 26 '26 05:01

James Nine


2 Answers

You should be able to use awk for this, something like:

du -b * | awk '{printf "%10.1f %s\n", $1/1000, $2}'

As in the following transcript:

pax> ls -l
total 3092
-rwxrwxrwx  1 pax   pax       807 2008-09-14 08:26 combo.pl*
-rwxrwxrwx  1 pax   pax       236 2008-09-14 08:26 match.pl*
-rwxrwxrwx  1 pax   pax       754 2008-09-14 08:26 mkdb.pl*
-rwxrwxrwx  1 pax   pax       689 2008-09-14 08:26 nine.pl*
-rwxrwxrwx  1 pax   pax   2089522 2008-05-25 21:06 words.db*
-rwxrwxrwx  1 pax   pax   1044761 2008-05-25 21:06 words.txt*

pax> du -b *
807       combo.pl
236       match.pl
754       mkdb.pl
689       nine.pl
2089522   words.db
1044761   words.txt

pax> du -b * | awk '{printf "%10.1f %s\n", $1/1000, $2}'
       0.8 combo.pl
       0.2 match.pl
       0.8 mkdb.pl
       0.7 nine.pl
    2089.5 words.db
    1044.8 words.txt
like image 198
paxdiablo Avatar answered Jan 27 '26 22:01

paxdiablo


You could use the du -k flag to report in Kilobytes?

On Linux, an alternative would be to not use du, but instead use find to report sizes in bytes, and then do the math with perl, awk, whatever.

du reports disk usage, so it includes sizes of directory entries. If you just want the sizes of actual files, find will give you that.

find . -type f -printf "%s %p\n" | perl -pe 's|^(\d+)(.*)|sprintf("%10.1f", $1/1000).$2|e;'

If you only want the total of the file sizes:

find . -type f -printf "%s\n" | perl -ne '$s+=$_; END{printf "%-10.1f\n", $s/1000}'
like image 32
mivk Avatar answered Jan 27 '26 22:01

mivk