【问题标题】:Perl regular expression loop through all the directory and get specific filePerl正则表达式遍历所有目录并获取特定文件
【发布时间】:2016-10-07 02:01:03
【问题描述】:

我想将 unix 正则表达式翻译成 Perl 语言,以获取与某些条件相关联的特定文件。

假设现在我在/nfs/cs/test_case/y2016 调用totalResult.pl 目录中有Perl 脚本,该目录还包含很多目录,例如testWeek1、testWeek2、testWeek3...等。每个目录都包含子目录,例如 testCase1、testCase2、testCase3...等。并且每个testCase目录都包含一个文件调用.test_result,其中包含记录结果是成功还是失败。

所以我可以使用unix命令获取文件信息,例如:

wc /nfs/cs/test_case/y2016/testWeek1/testCase1/.test_result

如果想获取每个失败的目录和子目录的 test_results,我可以从 unix 中的当前路径 /nfs/cs/test_case/y2016 进行,例如:

grep -ri "fail" */*/.test_result

它会给我输出:

/nfs/cs/test_case/y2016/testWeek1/testCase1/.test_result:fail
/nfs/cs/test_case/y2016/testWeek3/testCase45/.test_result:fail
/nfs/cs/test_case/y2016/testWeek4/testCase12/.test_result:fail
.
.
...etc

如何通过编写 Perl 脚本来实现它,只需运行命令 perl testCase.pl 即可获得相同的输出?我是 unix 和 Perl 的新手,有人可以帮忙吗?

【问题讨论】:

    标签: perl unix


    【解决方案1】:
    # Collect names of all test files
    my @TestFiles = glob('/nfs/cs/test_case/y2016/*/*/.test_result');
    # Check test files for "fail"
    foreach my $TestFile ( @TestFiles ) {
      open(my $T,'<',$TestFile) or die "Can't open < $TestFile: $!";
      while(<$T>){
        if( /fail/ ) {
           chomp;
           print $TestFile,":",$_,"\n";
        }
      }
      close($T);
    }
    

    【讨论】:

    • 谢谢帮忙,已经成功了,请问glob和chomp有什么用?
    • glob 从带有 * 通配符的模式中抓取文件(创建文件列表)。 chomp 从行尾删除换行符(那里有一个,ow什么都不做)
    • 我使用 chomp 处理/打印以“\n”结尾的行和最后一行可能没有“\n”的相同方式。
    【解决方案2】:

    您还可以在 Perl 中使用反引号 (`) 运算符执行相同的 linux 命令。

    @result=`grep -ri "失败" */*/.test_result`;

    打印@结果;

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多