Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Combining Like Rows

Status
Not open for further replies.
Apr 8, 2001
8
0
0
US
Hi,

I have a .csv file that has thousands of rows. Many of the rows are the same except for last field which is the amount field. Below is just two rows from it. I need to know how I would combine the rows so it shows 1 row with the last field showing -2857.69.

My output would read

B459,DE3000,L745,MC666,PR9999,2002-01,-2857.69

instead of

B459,DE3000,L745,MC666,PR9999,2002-01,442.31
B459,DE3000,L745,MC666,PR9999,2002-01,-3300.00

Thanks
 
One way to do this is to create a hash with the key being all of the fields except the last one. Use the value field in the hash to total the last field for lines that have the same beginning fields. The following should do the trick.

Code:
$file = "file";
open(F, "$file") or die "Can't open $file: $!\n";
while(<F>) {
    chomp($_);
    ($key, $value) = $_ =~ m/(.+),(.+)$/;
    $hash{$key} += $value;
}
close(F);

$newfile = &quot;newfile&quot;;
open(NF, &quot;>$newfile&quot;) or die &quot;Can't open $newfile: $!\n&quot;;
foreach $key (keys %hash) {
    print NF &quot;$key,$hash{$key}\n&quot;;
}
close(NF);
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top