in reply to Match Line And Combine Into One Line
split on commas; make a key from the H-string and the second number (presumably a date); add text to the hash value for that key (include a space before the added text if there's already text in the key). If you want to keep the same order as the first match of a given key, you'll need to keep the keys in an array as well. Once done, loop thru the keys and output.
use strict; use warnings; my %hash = (); my @order = (); foreach (<DATA>) { chomp; my ($h,$d,$txt) = split /,/; my $k = join ',', $h, $d; push @order, $k unless exists $hash{$k}; $hash{$k} .= ' ' if $hash{$k}; $hash{$k} .= $txt; } foreach my $k (@order) { print "$k,$hash{$k}\n"; } __DATA__ H123456,20151209,THIS IS A TEST H123456,20151209,TO COMBINE ALL H123456,20151209,MY MATCHING LINES H123456,20151209,INTO THE FIRST LINE H123456,20151209,THAT MATCHES. H654321,20151209,MATCH LINES FOR THIS H654321,20151209,ACCT INTO THE H654321,20151209,TOP LINE OF THE ACCT H432165,20151209,SINGLE LINE FOR THIS ONE
H123456,20151209,THIS IS A TEST TO COMBINE ALL MY MATCHING LINES INTO +THE FIRST LINE THAT MATCHES. H654321,20151209,MATCH LINES FOR THIS ACCT INTO THE TOP LINE OF THE AC +CT H432165,20151209,SINGLE LINE FOR THIS ONE
If you can guarantee that they keys will always stay together, you can change the logic to not need a second loop, and just output the value of the old key once the key has changed; don't even need a hash in that version, just a $k and $txt
|
|---|