Minimalist
Minimalist

Reputation: 975

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

Upvotes: 0

Views: 122

Answers (2)

Matt Jacob
Matt Jacob

Reputation: 6553

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

Upvotes: 1

Automaton
Automaton

Reputation: 163

This isn't the most elegant way, but if you know it is 3 columns (and because you're truncating United States to Unit) then this works:

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

It'll give this output file (you can play with spacing or left/right column alignment by tweaking the printf):

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

Upvotes: 1

Related Questions