问题
Shortest and nicest way to delete all files from directory that match certain regex in Perl on Windows.
My example: delete all *.txt
files from directory, but leave tmp.txt
? Windows.
回答1:
# glob gets the names of all .txt files
# we apply grep to remove tmp.txt from the list
@files = grep (!/^tmp\.txt$/,glob('*.txt'));
# delete the files
unlink @files;
回答2:
chdir $dir or die $!;
unlink grep { $_ ne 'tmp.txt' } <*.txt>;
回答3:
While not perfect, maybe something long winded will help.
use strict;
use warnings;
my $dir = "/tmp";
my $posreg = '.*\.txt$';
my $nexreg = '^tmp\.txt$';
opendir(my DH, $dir) || die($!);
{
for my $file (grep { /$posreg/i
&& ! /$negreg/i
&& -f "$dir/$_" } readdir($DH))
{
unlink($file) || die($!);
}
}
closedir();
回答4:
All of the solutions above are potentially problematic if there a lot files in the directory (10,000 or more), because they all read in the entire list of files at once. The safe thing to do is iterate through the directory, rather than read it all at once. "readdir" can return just the next entry in scalar context. I recommend updating @hpvac's answer with a while loop that goes through the directory one entry at a time.
( If you are certain there will never be a huge number of files, the solutions above are workable. )
回答5:
There is a perl utility: prename
(rename
on most linuxes), just use that in combination with rm:
prename `s/(?!tmp.txt)\.txt$/DELETE_THIS_$&`
rm DELETE_THIS_*
After typing the answer I saw you asked for a Windows solution. I think your best bet is downloading the (Perl source) for prename, and editting that a little, so that it works with Windows.
来源:https://stackoverflow.com/questions/5193282/delete-files-that-match-regex