我有一个具有以下格式的文件:
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的选项,但是我还找不到任何东西。
提前谢谢。
发布于 2018-06-13 09:24:00
您误解了grep函数的作用。它计算传递给它的每个元素的表达式(在本例中为$name),如果为真,则返回该元素。如果$name包含一个值,那么它将始终为true,因此它将返回文件中的每一行,并始终打印“查找”结果。
相反,您希望使用正则表达式。这就是正则表达式的样子。
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>
https://stackoverflow.com/questions/50833142
复制相似问题