Hi all,
I want to sort a directory by file size, du -k |sort -nr is fine, but the output number is NOT friendly.
So how to sort more friendly with du -h ?
Hi all,
I want to sort a directory by file size, du -k |sort -nr is fine, but the output number is NOT friendly.
So how to sort more friendly with du -h ?
The problem with -h is that you end up with things like K, M and G for kB, MB, or GB (I think, I have no access to Linux right now to actually verify this). So you are better off using -k if you want to sort it.
I have an approach
du -k |sort -nr > sort_file.txt.
The output file will be like this:
3783749 .
5294 ./dir3
4790 ./dir3/dir5/dir1
3088 ./dir8
...
can you help me on how to convert the number from sort_file.txt to MB, GB format, like this:
3.6 GB .
5.2 MB ./dir3
4.7 MB ./dir3/dir5/dir1
3 MB ./dir8
...
Thanks
You can use awk to format the size field :
du -k | sort -nr | awk '
BEGIN {
split("KB,MB,GB,TB", Units, ",");
}
{
u = 1;
while ($1 >= 1024) {
$1 = $1 / 1024;
u += 1
}
$1 = sprintf("%.1f %s", $1, Units);
print $0;
}
' > sort_file.txt
Jean-Pierre
Thank Jean-Pierre,
your script with awk works, but the calculation is not correct.
My actual data like this:
126M /openoffice/bin
31M /openoffice/old_versions
but it report:
0.1 MB /openoffice/bin
0.0 MB /openoffice/old_versions
Could you please correct it!
Thank so much!
The awk script formats the result of the du -k command not du -h.
Jean-Pierre.
Oh, yes.
It's perfect! Jean