删除7天以上的文件


79

我在下面编写了以下命令来删除所有早于7天的文件,但是它不起作用:

find /media/bkfolder/ -mtime +7 -name'*.gz' -exec rm {} \;

如何删除这些文件?


5
name与之间应该有一个空格'*.gz'
2015年

Answers:


136

正如@Jos指出的那样,您错过了name和之间的空格'*.gz';也该命令使用加速-type f选项来运行该命令˚F仅尔斯。

因此,固定命令为:

find /path/to/ -type f -mtime +7 -name '*.gz' -execdir rm -- '{}' \;

说明:

  • find:用于找到unix命令˚F尔斯/ d irectories / 的油墨等
  • /path/to/:开始搜索的目录。
  • -type f:仅查找文件。
  • -name '*.gz':列出以结尾的文件.gz
  • -mtime +7:仅考虑修改时间超过7天的内容。
  • -execdir ... \;:对于找到的每个这样的结果,在中执行以下命令...
  • rm -- '{}':删除文件;该{}部分是查找结果被上一部分替代的地方。--表示命令参数的末尾避免对以连字符开头的文件提示错误。

或者,使用:

find /path/to/ -type f -mtime +7 -name '*.gz' -print0 | xargs -r0 rm --

人中发现

-print0 
      True; print the full file name on the standard output, followed by a null character 
  (instead of the newline character that -print uses). This allows file names that contain
  newlines or other types of white space to be correctly interpreted by programs that process
  the find output. This option corresponds to the -0 option of xargs.

效率更高,因为它等于:

rm file1 file2 file3 ...

相对于:

rm file1; rm file2; rm file3; ...

-exec方法一样


另一种更快的命令是使用exec的+终止符,而不是\;

find /path/to/ -type f -mtime +7 -name '*.gz' -execdir rm -- '{}' +

该命令rm仅在末尾运行一次,而不是每次找到文件时运行一次,该命令几乎与使用-deletemodern中的option一样快find

find /path/to/ -type f -mtime +7 -name '*.gz' -delete

3
为什么我最后不直接去-delete?为什么乱用+\;
rain01


2

小心删除带有find的文件。使用-ls运行命令以检查要删除的内容

find /media/bkfolder/ -mtime +7 -name '*.gz' -ls 。然后从历史记录中拉出命令并追加-exec rm {} \;

限制find命令可以造成的损害。如果只想从一个目录中删除文件,-maxdepth 1则如果键入错误,则阻止find遍历子目录或搜索整个系统/media/bkfolder /

我添加的其他限制是更具体的名称参数,例如-name 'wncw*.gz',添加一个比time更新的 名称-mtime -31,并引用搜索到的目录。如果要自动执行清理,这些尤为重要。

find "/media/bkfolder/" -maxdepth 1 -type f -mtime +7 -mtime -31 -name 'wncw*.gz' -ls -exec rm {} \;

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.