Hello - I'm trying to use Perl to run through a list of numbered folders (41..61) that have a txt file in each with a name like "ms_stem41" or "ms_stem10B.pl". I am grepping a line from these files then manipulating them. The files all start with "ms_stem". When I type "grep 'word' <path/ms_stem* " into a terminal, it works fine. When I try to put this into a Perl Script, it reads "ms_stem*" literally and won't match to anything. I've tried a lot of ways of doing this like .* .+ [0-9]* , nothing makes the system call the right files. I feel I'm doing something wrong with the quotes or the metacharacters, but can't seem to make it work. Please help! Thanks! Here's my code:

#!/usr/bin/perl -w
#for folders 41..60
for ($k=41; $k<61; $k++){
system("grep 'word' <Users/scripts/$k/ms_stem* >output1");

I assume you are shelling out because you don't know who to write it all in perl. Here is one way:

#!/usr/bin/perl -w
#for folders 41..60
open (my $OUT, ">>", "path/to/output1") or die "$!";
for my $k (41..61){
   opendir(my $DIR, "Users/scripts/$k") or die "$!";
   my @files = grep {/^ms_stem/} readdir $DIR;
   close $DIR;
   foreach my $file (@files) {
      open(my $FH, "<",  "Users/scripts/$k/$_") or die "$!";
      while(<$FH>){
         print $OUT $_ if /word/;
      }
      close($FH);
   }
}

This should be more efficient than starting a new process for each directory you are scanning over. The only thing I am not sure of is what you wanted to print to output1 if you locate "word" in the file. The line of the file (which my code should do) or the name of the file or the line number or what?

You are correct - I did not know how to write it all in perl. Thank you for your help! I do want to copy the line of the file into output1. I appear to be getting an error (use of uninitialized value in concatenation in the line that starts "open(my $FH...") but I think I should be able to work that out. Thanks again!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.