helloworld1234
helloworld1234

Reputation: 337

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?

Upvotes: 1

Views: 650

Answers (2)

AnFi
AnFi

Reputation: 10913

# 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);
}

Upvotes: 3

Magesh04
Magesh04

Reputation: 41

You can also execute the same linux command within Perl using back tick (`) operator.

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

print @result;

Upvotes: 0

Related Questions