#!/usr/bin/perl # Solution to problem when greping for a specific host by name from # an /etc/host file when there are several matches found; ######### /etc/host Simulation ########################## # Change from `grep $hostname /etc/hosts` # to # open ETCHOSTFILE "$etchost"; # @ETCHOST = ; # close(ETCHOSTFILE); ######## BEGIN ETCHOST SIMULATION ################ $random = int(rand(11125)); if($random > 9999) { $string = "testhost"; } else { $string = "testhost"."$random"; } $i = 0; while ($i < 10000) { $space = ''; $comment = ''; $domain = ''; $a = int(rand(255)); $b = int(rand(255)); $c = int(rand(255)); $d = int(rand(255)); $r = int(rand(5)); $c = int(rand(3)); $dm = int(rand(7)); if($r > 3) {$space = " ";} if($c > 1 and $r > 3) {$comment = "\#Comment Added";} if($dm > 6 and $c > 2) {$domain = " $string\.domain\.com";} elsif ($dm > 4 and $c < 3) {$domain = "\ttesthost${i}\.domain\.com";} $pushstring = "$a\.$b\.$c\.$d\t\ttesthost${i}${domain}${space}${comment}\n"; push @array, "$pushstring"; $i++; } push @array, "$a\.$b\.$c\.$d\t\ttesthost"; #print "@array\n"; #############END ETCHOST SIMULATION ################## #############BEGIN EXPLICIT MATCH #################### @found = grep(/$string/, @array); #print "\nfound:\n@found\n"; foreach $result(@found) { chomp($result); $result =~ s/\t/ /g; $result =~ s/\s+/ /g; ($ipaddress, $hostname, $NULL1, $NULL2) = split(/ /, "$result"); # print "\'$string\' = \'$hostname\'\n"; if("$hostname" eq "$string") { $found = "$result"; last; } } #############END EXPLICIT MATCH ###################### print "\n\n$string = \"${found}\"\n";