use Modern::Perl; my %files; while () { next unless /^(\d+.\d+.\d+.\d+)/; chomp; push @{ $files{$1} }, $_; } for my $ip ( keys %files ) { do { say "Zip $_ -> $ip.zip" } for @{ $files{$ip} }; } __DATA__ 192.168.1.1somestring.txt 192.168.1.1anotherRANDOMstring.txt 192.168.1.1.somerandom.docx 192.168.1.3somestring.txt 192.168.1.3anotherRANDOMstring.txt 192.168.1.3.somerandom.docxx #### Zip 192.168.1.1somestring.txt -> 192.168.1.1.zip Zip 192.168.1.1anotherRANDOMstring.txt -> 192.168.1.1.zip Zip 192.168.1.1.somerandom.docx -> 192.168.1.1.zip Zip 192.168.1.3somestring.txt -> 192.168.1.3.zip Zip 192.168.1.3anotherRANDOMstring.txt -> 192.168.1.3.zip Zip 192.168.1.3.somerandom.docx -> 192.168.1.3.zip