Mal*_*ari 103 command-line delete rm find
我写下面的命令来删除所有早于 7 天的文件,但它不起作用:
find /media/bkfolder/ -mtime +7 -name'*.gz' -exec rm {} \;
Run Code Online (Sandbox Code Playgroud)
如何删除这些文件?
αғs*_*нιη 180
正如@Jos 指出的那样,您错过了name
和之间的空格'*.gz'
;也该命令使用加速-type f
选项来运行该命令˚F仅尔斯。
所以固定的命令是:
find /path/to/ -type f -mtime +7 -name '*.gz' -execdir rm -- '{}' \;
Run Code Online (Sandbox Code Playgroud)
find
:用于找到unix命令˚F尔斯/ d irectories /升的油墨等/path/to/
: 开始搜索的目录。-type f
: 只找到文件。-name '*.gz'
: 列出以.gz
.结尾的文件。-mtime +7
: 只考虑修改时间超过7天的。-execdir ... \;
:对于找到的每个这样的结果,在...
.rm -- '{}'
: 删除文件;该{}
部分是将查找结果替换为前一部分的位置。--
意味着命令参数的结尾避免对以hyphen开头的文件提示错误。find /path/to/ -type f -mtime +7 -name '*.gz' -print0 | xargs -r0 rm --
Run Code Online (Sandbox Code Playgroud)
从man 找到:
-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.
Run Code Online (Sandbox Code Playgroud)
哪个更有效,因为它相当于:
rm file1 file2 file3 ...
Run Code Online (Sandbox Code Playgroud)
与:
rm file1; rm file2; rm file3; ...
Run Code Online (Sandbox Code Playgroud)
就像在-exec
方法中一样。
另一种更快的命令是使用 exec 的+
终止符而不是\;
:
find /path/to/ -type f -mtime +7 -name '*.gz' -execdir rm -- '{}' +
Run Code Online (Sandbox Code Playgroud)
这个命令rm
只会在最后运行一次,而不是每次找到一个文件时,这个命令几乎和-delete
现代中使用选项一样快find
:
find /path/to/ -type f -mtime +7 -name '*.gz' -delete
Run Code Online (Sandbox Code Playgroud)
小智 10
小心使用 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 {} \;