命令行:管道查找结果到rm

jer*_*iuh 129 unix command-line rm find

我正在尝试删除超过15天的sql文件的命令.

查找部分正在工作但不是rm.

rm -f | find -L /usr/www2/bar/htdocs/foo/rsync/httpdocs/db_backups -type f  \( -name '*.sql' \) -mtime +15
Run Code Online (Sandbox Code Playgroud)

它会列出我想删除的文件列表,但不会删除它们.路径是正确的.

usage: rm [-f | -i] [-dIPRrvW] file ...
       unlink file
/usr/www2/bar/htdocs/foo/rsync/httpdocs/db_backups/20120601.backup.sql
...
/usr/www2/bar/htdocs/foo/rsync/httpdocs/db_backups/20120610.backup.sql
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

Lev*_*sky 250

你实际上是管道rm输出到输入find.你想要的是使用的输出find作为参数rm:

find -type f -name '*.sql' -mtime +15 | xargs rm
Run Code Online (Sandbox Code Playgroud)

xargs是将其标准输入"转换"为另一个程序的参数的命令,或者,因为它们更准确地将它们放在man页面上,

从标准输入构建和执行命令行

请注意,如果文件名可以包含空格字符,则应该更正:

find -type f -name '*.sql' -mtime +15 -print0 | xargs -0 rm
Run Code Online (Sandbox Code Playgroud)

但实际上,find有一个快捷方式:-delete选项:

find -type f -name '*.sql' -mtime +15 -delete
Run Code Online (Sandbox Code Playgroud)

请注意以下警告man find:

  Warnings:  Don't  forget that the find command line is evaluated
  as an expression, so putting -delete first will make find try to
  delete everything below the starting points you specified.  When
  testing a find command line that you later intend  to  use  with
  -delete,  you should explicitly specify -depth in order to avoid
  later surprises.  Because -delete  implies  -depth,  you  cannot
  usefully use -prune and -delete together.
Run Code Online (Sandbox Code Playgroud)

PS请注意,直接使用管道rm不是一个选项,因为rm不希望标准输入上的文件名.你目前正在做的是向后管道.


小智 25

find /usr/www/bar/htdocs -mtime +15 -exec rm {} \;
Run Code Online (Sandbox Code Playgroud)

将在/usr/www/bar/htdocs超过15天的时间内选择文件并将其删除.


Gau*_*mar 5

另一种更简单的方法是使用locate命令。然后,将结果通过管道传输到xargs.

例如,

locate file | xargs rm
Run Code Online (Sandbox Code Playgroud)


Alb*_*lla 5

使用xargs传递参数,并使用选项-rd '\n'忽略名称中的空格:

“${命令}”| xargs -rd '\n' rm

如果您还想删除只读文件,请包含--force 。