以下是一些 Perl 工具,可用于执行您所描述的操作:
- File::Find将对目录及其子目录中的文件进行递归搜索,
\&wanted
针对每个文件运行代码(文档中的回调)以确定它是否符合您的条件
- 操作员会
-r
告诉您文件是否可读 ( if (-r $file_name)...
)
- open将让您访问该文件并
<$fh>
读取其内容,以便您可以使用正则表达式检查它们是否与您的目标模式匹配
- 添加
\b
到模式的开头和结尾将导致它仅在单词边界处匹配,类似于grep
's -w
switch
如果您有更具体的问题,请使用演示这些问题的代码发布其他问题,包括说明您预期会发生什么以及实际结果与您的预期有何不同,我们很乐意帮助解决这些问题。
编辑:从注释中清理和运行的代码版本:
#!/usr/bin/env perl
use strict;
use warnings;
use 5.010;
use File::Find;
# Get $dirname from first command-line argument
my $dirname = shift @ARGV;
find(\&do_process, $dirname); # quotes around $dirname weren't needed
my ($KeyMnode, $KeyThreads);
sub do_process {
# chomp($_); - not needed; $_ isn't read from a file, so no newline on it
if (-r $_) { # quotes around $_ weren't needed
# $_ is just the final part of the file name; it may be better for
# reporting the location of matches to set $file_name to
# $File::Find::name instead
my $file_name = $_;
open(my $fh, '<', $file_name); # Use three-arg open!
while (<$fh>) {
chomp();
# Note that, if you store all matches into the same scalar values,
# you'll end up with only the last value found for each pattern; you
# may want to push the matches onto arrays instead.
if (/\bkeyword : Multinode\b/i) { $KeyMnode = "$file_name:$_"; }
if (/\bkeyword : Threads\b/i) { $KeyThreads = "$file_name:$_"; }
}
}
}