2013-02-19 84 views
0

我有图案像“关键词:多节点”。现在,我需要在目录中的所有文件中搜索此模式。如果我们在任何文件中都找到了模式,则应该返回一个非空字符串。它可能包含文件名或目录名模式搜索目录中的

在shell脚本下面将做同样的

KeyMnode = grep -w "keyword : Multinode" ${dirname}/*

我想通过使用find(子程序,目录路径)和子程序内我想要遍历整个目录中的所有条目。对于每一个条目,我想检查它是否是可读文件。如果文件可读,我想在找到的文件中搜索所需的模式“关键字:多节点”。如果我们击中成功,整个find命令应该会产生一个非空字符串(最好只是现有的目录名称),否则会产生一个空字符串。如果您需要更多信息,请告诉我。

我想这用perl来完成。请帮助我解决方案。

回答

0

这里有一些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:$_"; } 
    } 
    } 
} 
+0

找到(\&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

+0

我试图像上面和我,我希望的解决方案。你能告诉我,如果它可以进一步优化或足够进一步进行?谢谢 – ybc 2013-02-19 09:54:10

+0

@ybc:我已经编辑了我的答案,在评论中加入了一个已清理的代码版本,并添加了一些注释。 – 2013-02-19 12:52:55