这里有一些Perl的工具,这将是在做你所描述的有用:
- File::Find会为目录中的文件和它的孩子递归搜索,运行代码(
\&wanted
回调的文档)对每一个来确定是否符合您的条件或不
- 的
-r
运营商将告诉你一个文件是否可读(if (-r $file_name)...
)
- open将让你访问文件和
<$fh>
WIL我读出了它的内容,这样就可以用正则表达式检查他们是否你的目标模式相匹配
- 添加
\b
的开头和模式的结束将导致其在字边界只匹配,类似grep
的-w
开关
如果您有更具体的问题,请发布其他代码以展示他们的问题,包括您预期会发生什么以及实际结果与您的期望有何不同,并且我们很乐意帮助解决这些问题。
编辑:清理,从评论的代码可运行版本:
#!/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:$_"; }
}
}
}
找到(\&do_process, “$目录名”); sub do_process { chomp($ _); \t \t 如果(-r “$ _”){ \t \t $ FILE_NAME = $ _; \t \t open(my $ fh,“<$ file_name”); \t \t 而(<$fh>) \t { \t \t \t 格格(); \t \t 如果(/ \ bkeyword:多节点\ B/I) \t \t { \t \t \t \t $ KeyMnode = “$ FILE_NAME:$ _”; \t \t \t } \t \t \t \t \t 如果(/ \ bkeyword:线程\ B/I) \t \t { \t \t \t \t $ KeyThreads = “$ FILE_NAME:$ _”; \t \t } \t \t \t \t \t \t} \t} \t } – ybc 2013-02-19 09:51:11
我试图像上面和我,我希望的解决方案。你能告诉我,如果它可以进一步优化或足够进一步进行?谢谢 – ybc 2013-02-19 09:54:10
@ybc:我已经编辑了我的答案,在评论中加入了一个已清理的代码版本,并添加了一些注释。 – 2013-02-19 12:52:55