尝试使用 RegEx 在文件中查找特定字符串
Trying to find a specific string in a file with 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),目标是不重复文件中存在的主机。
我有以下代码来执行此操作,但它总是告诉我 "found" 我在键盘上输入的所有名称。
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;
}
我正在搜索将 RegEx 与 STDIN 方法结合使用的选项,但我还找不到任何东西。
提前致谢。
您误解了 grep
函数的作用。它为传递给它的每个元素计算表达式(在本例中为 $name
),如果为真,则该元素为 returned。如果 $name
包含一个值,那么它将始终为真,因此它会 return 文件中的每一行,并且它将始终打印 "Found" 结果。
相反,您想使用正则表达式。这就是正则表达式的样子。
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>
我有一个格式如下的文件:
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),目标是不重复文件中存在的主机。
我有以下代码来执行此操作,但它总是告诉我 "found" 我在键盘上输入的所有名称。
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;
}
我正在搜索将 RegEx 与 STDIN 方法结合使用的选项,但我还找不到任何东西。
提前致谢。
您误解了 grep
函数的作用。它为传递给它的每个元素计算表达式(在本例中为 $name
),如果为真,则该元素为 returned。如果 $name
包含一个值,那么它将始终为真,因此它会 return 文件中的每一行,并且它将始终打印 "Found" 结果。
相反,您想使用正则表达式。这就是正则表达式的样子。
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>