Chong Zheng Lun Chong Zheng Lun - 2 months ago 7
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

/nfs/cs/test_case/y2016
call totalResult.pl, 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
/nfs/cs/test_case/y2016
in unix like:

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


It will give me the output:

/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


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

Answer
# 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;
  while(<$T>){
    if( /fail/ ) {
       chomp;
       print $TestFile,":",$_,"\n";
    }
  }
  close($T);
}