How can I clean up misaligned columns in text?

前端 未结 6 662
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-31 09:08

I have a C program that outputs two columns, utterly misaligned. The reason for the misalignment is lengths of words in the first column are very different.

I have an o

6条回答
  •  醉话见心
    2021-01-31 09:39

    I wrote a small program that solves this problem using Perl. It also works for multiple columns.

    #!/usr/bin/perl
    use strict;
    use warnings;
    my $sep = 2;
    
    sub max {
        my ($a,$b) = @_;
        return $a > $b ? $a : $b;
    }
    
    my @rows;
    my $cols;
    my $max = 0;
    
    while (<>) {
        next if m/^\s*$/;
        my (@cols) = split m'\s+';
    
        for (@cols) {
            $max = max($max, length);
        }
    
        $cols = @cols;
        push @rows, \@cols;
    }
    
    for (@rows) {
        my $str = join '', (('%-' . ($max+$sep) . 's') x $cols);
        $str .= "\n";
        printf $str, @$_;
    }
    

提交回复
热议问题