2ck

dubar.pl

2ck
Apr 29th, 2012
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Perl 1.67 KB | None | 0 0
  1. #!/usr/bin/env perl
  2. # transforms this:
  3. #  <bytes> <path>
  4. # into this:
  5. #  <human_readable> <path> <nice_looking percentage bar>
  6. # meant to be used with the du utility
  7. use strict;
  8. sub string_round
  9. {
  10.     if (scalar(@_) < 1)
  11.     {
  12.         return;
  13.     }
  14.     my ($float, $precision)= @_;
  15.     if (!$precision)
  16.     {
  17.         $precision=2;
  18.     }
  19.     sprintf "%.${precision}f", $float;
  20. }
  21.  
  22. sub prettybyte
  23. {
  24.     my $n = shift;
  25.     my $precision = shift;
  26.  
  27.     my $unit = 1024;
  28.     my @affix = qw/B KiB MiB GiB TiB/;
  29.     my $affix_c = 0;
  30.  
  31.  
  32.     while (($n > $unit) and ($affix_c < (scalar @affix)-1)) {
  33.         $n/=$unit;
  34.         $affix_c++;
  35.     }
  36.     return string_round(${n}, $precision) . " $affix[$affix_c]";
  37. }
  38.  
  39. sub bar
  40. {
  41.     my ($width, $max, $value) = @_;
  42.     $width = $width - 2;
  43.     my $bar = "[";
  44.     for (0 .. $width * $value / $max)
  45.     {
  46.         $bar .= '=';
  47.     }
  48.     for ($width * $value / $max .. $width)
  49.     {
  50.         $bar .= ' ';
  51.     }
  52.     $bar .= "]";
  53. #$bar;
  54. }
  55.  
  56. my $max_path_len = 0;
  57. my $max_bytes = 0;
  58. my @byteslist = ();
  59. my @pathlist = ();
  60. while (my $line = <STDIN>)
  61. {
  62.     chomp($line);
  63.     my ($bytes, $path) = split /[[:space:]]+/, $line, 2;
  64.     if ($max_bytes < $bytes)
  65.     {
  66.         $max_bytes = $bytes;
  67.     }
  68.     if ($max_path_len < length($path))
  69.     {
  70.         $max_path_len = length($path);
  71.     }
  72. #print $bytes . "\n";
  73.     push @byteslist, $bytes;
  74.     push @pathlist, $path;
  75. }
  76.  
  77. my $i;
  78. my $barwidth = 40;
  79. for ($i = 0 ; $i < scalar(@byteslist); $i++)
  80. {
  81.     printf "%11s  %-${max_path_len}s  %${barwidth}s\n", prettybyte($byteslist[$i] * 1024, 2), $pathlist[$i],
  82.            bar(${barwidth},  $max_bytes, $byteslist[$i]);
  83. }
Advertisement
Add Comment
Please, Sign In to add comment