user2966554
user2966554

Reputation: 11

How to merge multiple lines in a csv file using Perl

Please help me in writing a code which will merge the lines of a csv file. My csv file is as shown below,

output.csv

abc,1,2,3,4,5
abc,3,5,60,3
abc,4,5,6
def,2,5,6,7
def,3,4,5,6

This is just an example. my csv file data keeps on changing each time. So, it is not limited to abc ( 3 rows) or def( 2 rows). Please help me to put the code so my csv file displays as shown below:

output.csv

abc,1,2,3,4,5,3,5,60,3,4,5,6
def,2,5,6,7,3,4,5,6

I tried reading csv using Text::CSV and tried hash. But I got stuck up when I tried to convert array to hash. I'm little confused here.Please help me out.

Upvotes: 1

Views: 1057

Answers (3)

Kenosis
Kenosis

Reputation: 6204

Here's another option:

use strict;
use warnings;

my %hash;
while (<>) {
    $hash{$1} .= $2 if /(.+?)(,.+)/;
}

print "$_$hash{ $_ }\n" for sort keys %hash;

Usage: perl script.pl inFile [>outFile]

The last, optional parameter directs output to a file.

Output on your dataset:

abc,1,2,3,4,5,3,5,60,3,4,5,6
def,2,5,6,7,3,4,5,6

Hope this helps!

Upvotes: 1

jkshah
jkshah

Reputation: 11703

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

my %hash;

open my $ifh, '<', 'input.csv' or die $!;
open my $ofh, '>', 'output.csv' or die $!;

while (<$ifh>) {
  chomp;
  my @F = split /,/;
  my $key = shift @F;
  push @{$hash{$key}}, @F;
}

foreach (sort keys %hash) {
  print $ofh "$_," . join (',', @{$hash{$_}}) . "\n";
}

close $ifh;
close $ofh;

Upvotes: 2

Joseph R.
Joseph R.

Reputation: 805

Assuming the first field doesn't contain commas:

perl -nle '
    ($key,$vals) = /^([^,]+),(.*)/;
    push @{$final_lines{$key}},$vals;
    END{
        for $key (sort keys %final_lines){
            print join ",",$key,@{$final_lines{$key}}
        }
    }
' < input_file > output_file

Upvotes: 4

Related Questions