Search code examples
perliotruncation

PERL to Truncate Input Columns Text Files for Output


I know there are several examples for truncation in Perl, however for this code objective I have not found a solution in truncating on a text file with 3 columns.

My goal is to use PERL to truncate the 3 columns on a text file to 4 chars only when reading and writing to a text file.

My INPUT text file - input.txt: [Column numbers 1,2,3 and only for reference]

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

The text file is not tab delimited but only spaces.

My desire OUTPUT file -- output.txt:

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

Instead my output.txt displayed:

Rain    Snow    Cloudy

Here is my code:

#!/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 $_;         
}

Solution

  • As a one-liner:

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

    As an actual program (five whole lines):

    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