regex - 尝试使用 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 的选项,但我找不到任何东西。
提前致谢。
解决方案
您误解了该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>
推荐阅读
- android - Xamain.Forms (Android) - 签名的 APK - 应用程序崩溃版本 5.1 (API 22)
- validation - 验证实时搜索 Vuew
- python - 无法单击下拉列表硒中的选项
- java - 基于条件 JSP 显示 HTML 代码
- javascript - V8:异构数组文字
- python - 为什么RNN的隐藏状态在训练中几乎变成-1或1
- python - 如何遍历项目列表并使用 Selenium 和 Python 提取特定部分
- django - Django:将数据链接到 ManyToManyField
- linux - 简单——使用 cronjob 运行 shell 脚本
- kubernetes - kubernetes:如何下载和上传图像到内部网络