Chong Zheng Lun Chong Zheng Lun - 1 year ago 72
Perl Question

Perl regular expression loop through all the directory and get specific file

I would like to translate the unix regular expression into Perl language to get some specific file associated with some condition.

Suppose now I have Perl script in a directory

call, this directory also contains lot of directories as well such as testWeek1, testWeek2, testWeek3...etc. Each directory contain sub-directory such as testCase1, testCase2, testCase3...etc. and Each testCase directory contains a file call .test_result, the contain record the result either success or fail.

So I can get the file information using unix command, for example:

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

If would like to get the test_results for each directory and sub-directory which is fail, I can do it from the current path
in unix like:

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

It will give me the output:


How can I achieve it in writing a Perl script just run the command
then can get the same output? I'm new in unix and Perl, anyone can help?

Answer Source
# 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;
    if( /fail/ ) {
       print $TestFile,":",$_,"\n";
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download