command to layout tab separated list nicely
So, the answer becomes:
column -t file_name
Note that this splits columns at any whitespace, not just tabs. If you want to split on tabs only, use:
column -t -s $'\t' -n file_name
The -s $'\t'
sets the delimiter to tabs only and -n
preserves empty columns (adjacent tabs).
P.S.: Just want to point out that the credit goes to Alex as well. The original hint was provided by him as a comment to the question, but was never posted as an answer.
Here's a script to do it:
aligntabs.pl
#!/usr/bin/perl
my $delim = '\s*\t\s*';
my %length = ();
my @lines = ();
for my $line (<>) {
chomp $line;
my @words = split $delim, $line;
my $numwords = scalar(@words);
for my $i (0..$numwords-1) {
my $maxlen = $length{$i} // 0;
my $thislen = length($words[$i]);
$maxlen = ($thislen > $maxlen)? $thislen: $maxlen;
$length{$i} = $maxlen;
}
push @lines, [@words];
}
foreach my $wordsref (@lines) {
my @words = @$wordsref;
my $numwords = scalar(@words);
for my $i (0..$numwords-1) {
if ($i < $numwords-1) {
my $fieldlen = $length{$i};
printf "%-${fieldlen}s ", $words[$i];
}
else {
print $words[$i];
}
}
print "\n";
}
usage
$ aligntabs.pl < infile
var1 var2 var3
var_with_long_name_which_ruins_alignment var2 var3
For manual tab stops: expand -t 42,48
For automatic tab stops, as suggested by alex: column -t
(expand
is on all POSIX systems. column
is a BSD utility, available in many Linux distributions as well.)