【问题标题】:PERL to Truncate Input Columns Text Files for OutputPERL 截断输入列文本文件以输出
【发布时间】:2018-09-26 21:03:16
【问题描述】:

我知道 Perl 中有几个截断示例,但是对于这个代码目标,我还没有找到截断具有 3 列的文本文件的解决方案。

我的目标是仅在读取和写入文本文件时使用 PERL 将文本文件上的 3 列截断为 4 个字符。

我的 INPUT 文本文件 - input.txt:[列号 1,2,3,仅供参考]

   1                       2                   3
   Rain                  65.22             London
   Snow                  34.44             United States
   Cloudy                23.00             Germany

文本文件不是制表符分隔的,只有空格。

我想要的OUTPUT文件——output.txt:

1                      2                    3
Rain                  65.2                  Lond
Snow                  34.4                  Unit
Clou                  23.0                  Germ

显示的是我的 output.txt:

Rain    Snow    Cloudy

这是我的代码:

#!/usr/bin/perl
use strict;
use warnings;


my $input = 'input.txt';

#open file for reading
open my $fhIn, '<', $input or die qq(Unable to open "$input" for input: $!);

#open file for writing
my $output = 'output.txt';
open my $fhOut, '>', $output or die "Can't create output.\n";


while( <$fhIn>) {

     (s/.{4}\K.*//s);
     print  $fhOut $_;         
}

【问题讨论】:

    标签: perl io truncation


    【解决方案1】:

    作为单行:

    $ perl -F'/\s{2,}/' -wlane 'print join("  ", map { substr($_, 0, 4) } @F)' a.txt
    

    作为一个实际的程序(五个整行):

    use strict;
    use warnings;
    
    while (<DATA>) {
        print join('  ', map { substr($_, 0, 4) } split(/\s{2,}/)) . "\n";
    }
    
    __DATA__
    Rain                  65.22             London
    Snow                  34.44             United States
    Cloudy                23.00             Germany
    

    【讨论】:

      【解决方案2】:

      这不是最优雅的方式,但如果您知道它是 3 列(并且因为您将 United States 截断为 Unit),那么这可行:

      #!/usr/bin/perl
      use strict;
      use warnings;
      
      my $input = 'input.txt';
      open my $fhIn, '<', $input or die qq(Unable to open "$input" for input: $!);
      
      my $output = 'output.txt';
      open my $fhOut, '>', $output or die "Can't create output.\n";
      
      while(<$fhIn>) {
          s/^\s+//;
          my ($f1, $f2 , $f3) = split /\s+/;
          $f1 = substr $f1, 0, 4;  
          $f2 = substr $f2, 0, 4;  
          $f3 = substr $f3, 0, 4;  
          printf $fhOut "%-4s %-4s %-4s\n",$f1,$f2,$f3; 
      }
      

      它会给出这个输出文件(你可以通过调整 printf 来调整间距或左/右列对齐):

      1    2    3   
      Rain 65.2 Lond
      Snow 34.4 Unit
      Clou 23.0 Germ
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-10-30
        • 2017-04-23
        • 1970-01-01
        相关资源
        最近更新 更多