Search code examples
regexstringperlfilestdin

Trying to find a specific string in a file with RegEx


I have a file with the following format:

define host{
     use             generic-printer
     host_name       imp-p-125
     address         100.68.22.10
     hostgroups      network-printers
    }

 define service{
        use     generic-service
        host_name       imp-p-125
        service_description     Toner 1 Status
        check_command   check_toner1
        check_interval  240
        retry_interval  2
        notification_interval   245
        }

I'm trying to find the host_name line (1imp-p-1251), with the objetive to not repeat a host that exists in the file.

I have the following code to do this, but it's always telling me "found" for all the names that I put in the keyboard.

sub openFile {

  open(FILE, "/home/server/test2.txt");
  print "file open!\n";
  print "hostname(Example 'imp-p-125'): ";

  my $name = <STDIN>;
  chomp $name;

if (grep{$name} <FILE>){
      print "found\n";
}else{
    print "word not found\n";
}
  close FILE;
}

I was searching options to use a RegEx with STDIN method, but I can't find anything yet.

Thanks in advance.


Solution

  • You've misunderstood what the grep function does. It evaluates the expression (in this case $name) for each element passed to it and if true, that element is returned. If $name contains a value, then it'll always be true, so it'll return every line in file and it'll always print the "Found" result.

    Instead you want to use a regular expression. This is what a regular expression looks like.

    if($somevalue =~ /pattern/)
    

    You want to process every line so you'll also need a loop, like a while loop. If you leave out $somevalue, like many Perl functions and operators, it'll default to $_ which is what this loop will use to give you each line of the file. And since $name might contain characters that are considered special in regular expressions, surrounding it with \Q and \E means it'll be treated as just regular characters.

    my $found=0;
    while(<FILE>)
      {
      if( /\Q$name\E/ )
        {
        $found=1;
        }
      }
    if($found)
      {
      print "Found\n";
      }
    else
      {
      print "word not found\n";
      }
    

    You're also using an outdated method of opening the file and also not checking it opened. Consider replacing it with this

    if(open(my $file, "<", "/home/server/test2.txt"))
      {
      # Your code to process the file goes inside here
      close($file);
      }
    

    PS Don't forget to replace <FILE> with <$file>