如何通过匹配perl中的模式来读取目录中的多个文件?

时间:2016-06-03 11:00:21

标签: perl

如何通过匹配模式来读取目录中的多个文件?

我有一个包含几个目录的目录。每个目录都包含一个' .log'文件和名为Cov_work的目录。目录中的每个日志文件都有一个" Pass"字符串或"失败"串。我需要将两者分开并将.log与传递字符串一起存储在新目录中以及Cov_work。我能够传输文件,但不能传输目录。我为我的第一篇文章道歉,因为它有点混乱。该计划如下:

#!/usr/bin/perl

use strict;
use warnings;
use File::Copy::Recursive qw(fcopy rcopy dircopy fmove rmove dirmove);

my $dir  = ("/home/Narayanan/Cov_script/logs");
my $home  = ("/home/Narayanan/Cov_script");
my $dest_dir = "Pass_dir";
my $dest_dir1 = ("/home/Narayanan/Cov_script/Pass_dir/");


   if (-e $dest_dir) {
        print "$dest_dir already exists\n";
   } else {
    system("mkdir $dest_dir");
   }

my @file =   `grep "TEST HAS PASSED" $dir/*/*.log`;

my $cov = "Cov_work";

print "@file\n";

my $i=0;


    foreach my $cnt(@file){

           my $pf_names  = (split(/ /, $file[$i])) [-3];
       my $pf_names1 = (split(/:/, $pf_names)) [-2];

       my $cov_names  = $pf_names1;
       my @cov_names1 = split /\//, $cov_names;

       pop @cov_names1;
       my $cov_new2 = $cov_names1[-1];
       print ("1 : Last Element $cov_new2\n"); 

       $cov_names = join('/', @cov_names1);
       my $cov_names2 = ("$cov_names/$cov");

       if (-e $dest_dir1){

        system (chdir "$dest_dir1");
        system (mkdir "$cov_new2");
        system (chdir "$home");
       }
       else {
        print "Can't create the directory\n";
       }

       my $pass_path = ("$dest_dir1$cov_new2");
       print " Moved Location : $pass_path\n";

       print " Cov : $cov_names\n";

       if (-e $pf_names1){

        print "$pf_names1\n";
        fcopy ($pf_names1, $pass_path);
        }
       else { 
        print "No path found\n";
    }

       if (-e $cov_names){

        print "Inside Cover loop: $cov_names2\n";
        dircopy ($cov_names2, $pass_path) or die "Can't copy";
        }
       else { 
        print "No cover report found\n";
    }

   $i++;
     }

print "$i\n";
$i=0;

1 个答案:

答案 0 :(得分:2)

欢迎来到stackoverflow!

为了给您提供一个具体且有用的解决方案来解决您的问题,您必须尽可能地指出您的问题。 出于您的解密,我得到以下信息:

  • 您的脚本使用文件
  • 您要将某些文件从目录a /复制到目录b /
  • 您可以打开每个文件并阅读它
  • 您要检查每个文件是否包含字符串PassFail
  • 您在复制文件方面没有任何问题

要解决您确切的问题,我们需要知道:

  • 这些文件是如何构建的
  • 你怎么读每个文件?
  • 字符串是否必须出现在一行的末尾,中间,开始?

尽管如此,我还是试一试。我假设您逐行读取文件 ,并且您可以单独处理每一行。 然后,您可以使用regex检查某些字符串是否出现。

... you read the file line by line and store
... temporary each line in the variable $line...
... for each line you check:
chomp($line);
if( $line =~ /^Pass$/ ){
  #the line begins immediatly with the string 'Pass' and after that the line
  #the line terminates
}
if( $line =~ /Pass/){
  #somewhere in the $line the String 'Pass' occurs
}
if( $line =~ /^Pass/){
  #the line starts with the String 'Pass'
}
if( $line =~ /Pass$/){
  #the line terminates with the String 'Pass'
}

当然,字符串Fail也是可以的。