#!/usr/bin/env perl use 5.010; use strict; use warnings; my ($host, %seen); while () { chomp; if (m{^hostname\d\.com}) { say $host = $_; } else { say unless $seen{$host}{$_}++; } } __DATA__ hostname1.com Gateway FAIL Gateway FAIL Gateway FAIL hostname2.com Gateway FAIL Gateway FAIL Gateway FAIL