my %record; my ( $id, $field ); while (<>) { chomp; if ( /^RECORD:\s+(\d+)/ ) { $id = $1; elsif ( /Field:\s/ ) { $field = $_; elsif ( /MSG#\s ) { $record{$id}{field} = $field; $record{$id}{msg} = $_; } } # now go through the %record set, output to csv...