Tuesday 15 May 2012

df ugly, DF pretty

The output from df is quite ugly, especially on Linux, Solaris; well, all of them.

Without further ago, a simple script I like to call DF which tidies it up considerably.

#!/usr/bin/env perl

use strict;

# code in this script is ever so slightly old-fashioned
# so that it works even back to Perl 5.006 (hello Solaris 8)

my $commas;
if($ARGV[0] eq '-commas') {
   shift;
   $commas = 1;
}

if($^O =~ /linux/) {
   open(DFD, "df -vkP @ARGV |")

     or die "Cannot open pipe from df: $!";
}
else {
   # this assumes Solaris

   # email if you have issues with other OS - we can fix it.
   open(DFD, "df -vk @ARGV |")
     or die "Cannot open pipe from df: $!";
}


sub fixup($$) {
   my ($l, $r) = @_;
   $l =~ s/ ( \d+)$/$1/;
   return "$l,$r";
}

sub commas($) {
   local $_ = $_[0];

   if($commas && /^\d+$/) {
       1 while s/(.*\d)(\d\d\d)/fixup $1, $2/e;
   }

   return $_;
}

my @row = map {
   chomp;


   # fix a column header that annoys the split
   my $x = s/Mounted on/Mounted-on/ ? 1 : 0;

   my $cols = [ map { commas $_ } split ];
   if($x && $^O !~ /linux/) {
       $x = pop @$cols;
       splice @$cols, 1, 0, $x;
   }

   $cols
} <DFD>;

# calculate max width of each column of each row
my @widths;
map {
   for(my $i = 0; $i < @$_; ++$i) {
       my $l = length $_->[$i];
       $widths[$i] = $l if $widths[$i] < $l;
   }
} @row;

$widths[0] *= -1;
$widths[4] *= -1;
$widths[5] *= -1;

# generate the format string
my $format = join('  ', map { "%${_}s" } @widths) . "\n";
printf $format, @$_ foreach @row;

exit 0;


No comments:

Post a Comment