1

I want to delete a column from csv file using perl, for that I am splitting the line on ",", but there are some columns with multiple values and hence multiple commas. That is each line may have different number of commas, so its hard to delete a column that I want to be deleted. Can you help in doing so?

2 Answers 2

2

For processing CSV files, use an actual csv parser like Text::CSV.

This will take care of the instances of fields enclosed in quotes because they contain commas.

Sign up to request clarification or add additional context in comments.

Comments

0

Suppose your file looks like

Tudor,Vidor,10,Hapci
Szundi,Morgo,7,Szende
Kuka,"Hofeherke, alma",100,Kiralyno
Boszorkany,Herceg,9,Meselo

and you want to find sum of 3rd column, but in 3rd row you see the 2nd column has value with comma so to handle that use Text::CSV as:

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

use Text::CSV;
my $csv = Text::CSV->new({ sep_char => ',' });

my $file = $ARGV[0] or die "Need to get CSV file on the command line\n";

my $sum = 0;
open(my $data, '<', $file) or die "Could not open '$file' $!\n";
while (my $line = <$data>) {
  chomp $line;

  if ($csv->parse($line)) {

      my @fields = $csv->fields();
      $sum += $fields[2];

  } else {
      warn "Line could not be parsed: $line\n";
  }
}
print "$sum\n";

If you'd prefer to access the fields in your CSV file by name, use Tie:Handle::CSV

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.