Shanmugam E
Shanmugam E

Reputation: 31

How to remove the last column from a CSV file using perl

How can I remove the trailing , from each row?

Existing CSV file:

S.NO,NAME,S1,S2,S3,S4,S5,       
1,aaaaaaa,66,88,77,55,99,       
2,bbbbbbb,55,66,88,99,77,           

The code is:

 #!/usr/bin/perl


  use strict;
  use warnings;


 open my $inn, '<', 'a1.csv' or die "Cannot open file for input: $!";
 open my $outt, '>', 'a2.csv' or die "Cannot open file for output: $!";

foreach my $line (<$inn>) {
  chomp $line;
  my @data = split /,/, $line;
  printf $outt "%s,%d\n", $data[0], scalar grep /^GO:/, @data;
 }   

My expected output CSV file:

S.NO,NAME,S1,S2,S3,S4,S5                  
1,aaaaaaa,66,88,77,55,99          
2,bbbbbbb,55,66,88,99,77

Upvotes: 0

Views: 205

Answers (2)

Dave Cross
Dave Cross

Reputation: 69244

When processing a file a line at a time, it is better to use while (which also reads the file a line at a time) rather than foreach (which reads the whole file before giving you the first line).

If you only want to remove the final comma, then there is no need to treat the file as a CSV file.

#!/usr/bin/perl

use strict;
use warnings;

open my $inn, '<', 'a1.csv' or die "Cannot open file for input: $!";
open my $outt, '>', 'a2.csv' or die "Cannot open file for output: $!";

while (<$inn>) {
  # Remove trailing comma on first line
  s/,$// if $. == 1;
  print $outt $_;
}

Upvotes: 2

daxim
daxim

Reputation: 39158

munge_column_names patch provided by Tux. This makes up unique names for each unnamed column header.

#!/usr/bin/perl
use strict;
use warnings;
use autodie;
use Text::CSV;
my @headers = qw(S.NO NAME S1 S2 S3 S4 S5);
my $csv_in = Text::CSV->new({binary => 1, auto_diag => 1});
my $csv_out = Text::CSV->new({binary => 1, auto_diag => 1});
open my $in, '<:encoding(UTF-8)', 'a1.csv';
open my $out, '>:encoding(UTF-8)', 'a2.csv';
my $eix = "001";
$csv_in->header($in, {munge_column_names => sub { s/^$/"E".$eix++/er; }});
$csv_out->say($out, [@headers]);
while (my $row = $csv_in->getline_hr($in)) {
    $csv_out->say($out, [$row->@{@headers}]);
}

Upvotes: 0

Related Questions