my %data; my $device; for (@check){ next if ! /\d{1,2}-\d{1,2}/; chomp; s/\s+//g; if (/EQUIP-OME/){ $device = $_; next; } push @{$data{$device}}, $_; } for my $device (keys %data){ for my $interface (@{$data{$device}}){ print "$device,$interface\n"; } }