删除匹配正则expression式的文件

最短和最好的方法来删除目录中的所有文件,匹配在Windows上Perl的某些正则expression式

我的例子:删除目录中的所有*.txt文件,但离开tmp.txt ? 视窗。

 # 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; 
 chdir $dir or die $!; unlink grep { $_ ne 'tmp.txt' } <*.txt>; 

虽然不完美,也许长时间的啰嗦会有所帮助。

 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(); 

如果目录中有很多文件(10,000或更多),则上述所有解决方案都可能会出现问题,因为它们都一次读取整个文件列表。 安全的做法是遍历目录,而不是一次读完。 “readdir”只能返回标量上下文中的下一个条目。 我建议用一个while循环更新@ hpvac的答案,一次一个目录地通过目录。

(如果你确定永远不会有大量的文件,上面的解决方案是可行的。)

有一个perl实用程序: prename (在大多数linuxes上rename ),只需结合使用rm:

 prename `s/(?!tmp.txt)\.txt$/DELETE_THIS_$&` rm DELETE_THIS_* 

输入答案后,我看到你问了一个Windows解决方案。 我认为你最好的选择是下载(Perl源代码),然后编辑一下,这样它就可以在Windows上使用。