首页 > 解决方案 > 尝试使用 RegEx 在文件中查找特定字符串

问题描述

我有一个格式如下的文件:

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
        }

我试图找到 host_name 行(1imp-p-1251),目的是不重复文件中存在的主机。

我有以下代码来执行此操作,但它总是告诉我“找到”了我在键盘中输入的所有名称。

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;
}

我正在搜索使用带有 STDIN 方法的 RegEx 的选项,但我找不到任何东西。

提前致谢。

标签: regexstringperlfilestdin

解决方案


您误解了该grep函数的作用。它评估$name传递给它的每个元素的表达式(在本例中),如果为真,则返回该元素。如果$name包含一个值,那么它将始终为真,因此它将返回文件中的每一行,并且始终打印“找到”结果。

相反,您想使用正则表达式。这就是正则表达式的样子。

if($somevalue =~ /pattern/)

你想处理每一行,所以你还需要一个循环,比如while循环。如果您$somevalue像许多 Perl 函数和运算符一样省略 ,它将默认使用$_哪个循环将用于为您提供文件的每一行。并且由于$name可能包含在正则表达式中被认为是特殊的字符,用 \Q 和 \E 包围它意味着它将被视为只是常规字符。

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

您还使用了一种过时的打开文件的方法,也没有检查它是否打开。考虑用这个替换它

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

PS不要忘记替换<FILE><$file>


推荐阅读