-
Notifications
You must be signed in to change notification settings - Fork 0
/
align
executable file
·62 lines (54 loc) · 1.83 KB
/
align
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#!/usr/bin/env perl
# ########################################################################
# This program is part of Aspersa (http://code.google.com/p/aspersa/)
#
# This program reads in lines and splits them into words. It counts how many
# words each line has, and if there is one number that predominates, it assumes
# this is the number of words in each line. Then it discards all lines that
# don't have that many words, and looks at the 2nd line that DOES. It assumes
# this is the first non-header line. Based on whether each word looks numeric
# or not, it decides on column alignment. Finally, it goes through and decides
# how wide each column should be, and then prints them out.
#
# This is useful for things like aligning the output of vmstat or iostat so it
# is easier to read.
#
# Author: Baron Schwartz
# ########################################################################
use strict;
use warnings FATAL => 'all';
# Finds the max element in the list
sub max {
my $i = shift @_;
foreach my $n ( @_ ) {
$i = $n if $n > $i;
}
return $i;
}
# Read all lines
my @lines;
my %word_count;
while ( <> ) {
my $line = $_;
my @words = $line =~ m/(\S+)/g;
push @lines, \@words;
$word_count{ scalar @words }++;
}
# Find max number of words per line
my @wc = reverse sort { $word_count{$a}<=>$word_count{$b} } keys %word_count;
my $m_words = $wc[0];
# Filter out non-conformists
@lines = grep { scalar @$_ == $m_words } @lines;
die "I need at least 2 lines" unless @lines > 1;
# Find the widths and alignments of each column
my @fmt;
foreach my $i ( 0 .. $m_words-1 ) {
my $m_len = max(map { length($_->[$i]) } @lines);
my $code = $lines[1]->[$i] =~ m/[^0-9.-]/ ? "%-${m_len}s" : "%${m_len}s";
push @fmt, $code;
}
my $fmt = join(' ', @fmt) . "\n";
# Print!
foreach my $l ( @lines ) {
printf $fmt, @$l;
}