代码之家  ›  专栏  ›  技术社区  ›  DKru

对多列文件中的每一列进行相同的编辑

  •  -1
  • DKru  · 技术社区  · 8 年前

    我有多个具有不同列数的CSV文件,需要将其重新格式化为固定格式的文本文件。

    以下是我目前的代码:

    use strict;
    use warnings;
    
    my $input = 'FILENAME.csv';
    my $output = 'FILENAME.txt';
    
    open (INPUT, "<", "$input_file") or die "\n !! Cannot open $input_file: $!";
    open (OUTPUT, ">>", "$output_file") or die "\n !! Cannot create $output_file: $!";
    
    while ( <INPUT> ) {
    
        my $line = $_;
        $line =~ s/\s*$//g;
    
        my ( $a, $b, $c, $d, $e, $f, $g, $h, $i, $j ) = split('\,', $line);
    
        $a = sprintf '%10s', $a;
        $b = sprintf '%10s', $b;
        $c = sprintf '%10s', $c;
        $d = sprintf '%10s', $d;
        $e = sprintf '%10s', $e;
        $f = sprintf '%10s', $f;
        $g = sprintf '%10s', $g;
        $h = sprintf '%10s', $h;
        $i = sprintf '%10s', $i;
        $j = sprintf '%10s', $j;
    
        print OUTPUT "$a$b$c$d$e$f$g$h$i$j\n";
    
    }
    
    close INPUT;
    close OUTPUT;
    
    exit;
    
    2 回复  |  直到 8 年前
        1
  •  3
  •   Borodin    8 年前

    你的意思是这样的吗?

    perl -aF/,/ -lne 'print map sprintf("%10s", $_), @F' FILENAME.csv > FILENAME.txt
    
        2
  •  -1
  •   Sobrique    8 年前

    任何时候使用序列变量时,都应该使用数组。在这种情况下,由于你只使用了一次数组,你甚至不需要做更多的事情,只是暂时保留它。

    #!/usr/bin/env perl
    
    use strict;
    use warnings;
    
    my $input_file  = 'FILENAME.csv';
    my $output_file = 'FILENAME.txt';
    
    my $format = '%10s';
    
    open( my $input_fh, "<", $input_file ) or die "\n !! Cannot open $input_file: $!";
    open( my $output_fh, ">>", $output_file ) or die "\n !! Cannot create $output_file: $!";
    
    while (<$input_fh>) {
       print {$output_fh} join "", map { sprintf $format, $_ } split /,/;
    }
    
    close $input_fh;
    close $output_fh;
    
    exit;