如何删除列之间的空格并在其中放置自定义数量的空格?

时间:2011-07-02 08:21:57

标签: vim alignment tabular

我有这个专栏:

     USA     France    212     13
  Canada      Spain     34     23
  Me ico      Italy      4    390
   india   Portugal   5900     32
Malaysia    Holland     15     43

我想删除这样的空格:

     USA  France 212 13
  Canada   Spain  34 23
  Me ico   Italy   4390
   indiaPortugal5900 32
Malaysia Holland  15 43

并在它们之间添加自定义数量的空格 (每列之间的空格数相同)。

有没有办法做到这一点?
(对于我的左右对齐表格)

修改:
  有谁知道如何检查列的内容(\%。c)?

2 个答案:

答案 0 :(得分:1)

使用'perl'的解决方案。我想第一列的宽度是8个字符。

程序:

use strict;
use warnings;

## Hash with contents of each line. Example:
## $file{ 1 } = "... line 1 ..."
## $file{ 2 } = "... line 2 ..."
## ...
my %file;

## Max. number of characters of each column.
## $col_length[0] will have the max. number of characters of all string of
## first column, and the same for the others.
my @col_length;

while ( <> ) {
        next if /^\s*$/;
        chomp;

        ## Save fixed columns in array.
        ## A8 -> 8 characters of first columns.
        ## A11 -> 11 characters of second column.
        ## ...
        my @line = unpack( "A8A11A7A7", $_ );

        ## Remove leading and trailing spaces of each field.
        @line = map { s/^\s*//; s/\s*$//; $_ } @line;

        ## Save max. number of characters of each column.
        for ( 0 .. $#line ) {
                my $l = length $line[$_];
                $col_length[$_] = $l > ($col_length[$_] || 0) ? $l : $col_length[$_]; 
        }

        ## Save each input line.
        push @{ $file{ $. } }, @line;
}

## Print to output.
for ( sort { $a <=> $b } keys %file ) {
        my $format = join "", (map { "%" . $_ . "s" } @col_length), "\n";
        printf $format, @{$file{ $_ }};
}

输入文件(infile):

     USA     France    212     13
  Canada      Spain     34     23
  Me ico      Italy      4    390
   india   Portugal   5900     32
Malaysia    Holland     15     43

执行:

$ perl script.pl infile

输出:

     USA  France 212 13
  Canada   Spain  34 23
  Me ico   Italy   4390
   indiaPortugal5900 32
Malaysia Holland  15 43

答案 1 :(得分:0)

据我所知,你需要做两遍。

在第一遍中,您需要确定所有字段的宽度,直到您完成整个列表后才能确定。例如,你不知道在到达葡萄牙的路线之前,你必须摆脱美国和法国之间的三个空间。

此后第二遍应该没问题。