删除数百万个文件 - oneliner

时间:2015-03-29 20:59:15

标签: perl file unix rm

我想删除目录中的数百万个文件,并提到以下Perl代码最快的页面:

perl -e 'chdir "BADnew" or die; opendir D, "."; while ($n = readdir D) { unlink $n }`

但是,是否也可以仅对包含单词' sorted'?的文件执行此操作。有谁知道怎么改写这个?

4 个答案:

答案 0 :(得分:2)

可以使用findgrep组合来完成:

find BADnew -type f -exec grep -q sorted {} \; -exec rm {} \;

仅当第一个的返回码为零时,才会执行第二个-exec命令。

你可以做干跑:

find BADnew -type f -exec grep -q sorted {} \; -exec echo {} \;

答案 1 :(得分:1)

核心模块File::Find将递归遍历所有子目录并对找到的所有文件执行子例程

perl -MFile::Find -e 'find( sub { open $f,"<",$_; unlink if grep /sorted/, <$f> }, "BADnew")'

答案 2 :(得分:1)

尝试:

find /where -type f -name \* -print0 | xargs -0 grep -lZ sorted | xargs -0 echo rm
#can search for specific ^^^ names                       ^^^^^^            ^^^^
#                                   what should contain the file            |
#                              remove the echo if satisfied with the result +

以上:

  • find搜索具有指定名称(* - any)
  • 的文件
  • xargs ... grep列表文件包含字符串
  • xargs rm - 删除文件
  • 不要死&#34; arg算得太长&#34;
  • 文件名称中可能有空格
  • 需要grep知道-Z
  • 的内容

也是一种变体:

find /where -type f -name \* -print0 | xargs -0 grep -lZ sorted | perl -0 -nle unlink

答案 3 :(得分:0)

尽管存在具体问题,您仍未明确说明是否需要文件 name 或文件内容来包含sorted。以下是两种解决方案

首先,chdir到您感兴趣的目录。如果您因任何原因确实需要单行,那么将chdir置于程序中是没有意义的。

cd BADnew

然后,您可以取消链接作为文件且名称包含sorted

的所有节点
perl -e'opendir $dh, "."; while(readdir $dh){-f and /sorted/ and unlink}'

或者您可以打开每个文件并阅读它以查看其内容是否包含sorted。我希望很明显,这种方法会慢得多,尤其是因为你必须阅读整个文件来建立负面的。请注意,此解决方案依赖于

perl -e'opendir $dh, "."; while(readdir $dh){-f or next; @ARGV=$f=$_; /sorted/ and unlink($f),last while <>}'
相关问题