PYPL
PYPL

Reputation: 1849

How can I delete all files that match a list of patterns with Perl?

I have a list of files and an array with some values that contains pattern of the filename

filename: awefsad-name1-x33

@array=("name1","name2","name3");

how to remove files that contain the name in array?

@files = ("*");
foreach $check(@files){
   foreach $i(@array){
      if($check =~ /\Q$i/){
          unlink $check;
      }
   }
}

Upvotes: 0

Views: 2062

Answers (2)

Miller
Miller

Reputation: 35198

Joining the regular expressions into a single expression yields this single for loop to unlink the files.

my $match_re = join '|', map {"\Q$_"} ("name1","name2","name3");

for my $file (grep {/$match_re/} <*>) {
    print "unlink $file\n";
}

Upvotes: 2

simbabque
simbabque

Reputation: 54333

You need to use the glob built-in to get your list of file names. You can also use qr// to precompile the patterns into regular expressions. Using good names will make it easier to read your code, and strict and warnings will tell you about errors and mistakes you made.

use strict;
use warnings;
use feature 'say'; # just for demonstration
my @patterns = map { qr/\Q$_/ } ( "name1", "name2", "name3" );

FILE: foreach my $file ( glob '*' ) {
  foreach my $pattern (@patterns) {
    if ($file =~ $pattern) {
      say $file or warn qq{cannot delete $file: $!}; # replace with unlink
      next FILE;
    }
  }
}

Edit: Note that you can only delete each file once, so we are done with the list of patterns as soon as we've matched one and gotten rid of the file.

I changed the unlink to say so you can take a look at what it matches. For me it works:

my @patterns = map { qr/\Q$_/ } ( 'scratch', '.txt' );

__END__
data.txt
file2.txt
scratch.pl
scratch2.pl

Upvotes: 1

Related Questions