[英]Linux - Deleting files (only) within nested directories
I have a set of user folders, where they can keep their PDFs. 我有一组用户文件夹,他们可以在其中保存PDF。 I want to create a cron job which would delete all files which are over a week old (and files only, not directories) within all the nested directories. 我想创建一个cron作业,该作业将删除所有嵌套目录中超过一个星期的所有文件(仅文件,而不是目录)。
So, my directory structure looks as following: 因此,我的目录结构如下所示:
users
│ index.html
│
+---+ a-long-string-of-random-characters-1
| │ file1.pdf
│ │ file2.pdf
│
|
+---+ a-long-string-of-random-characters-2
│ │ file1.pdf
│ │ file2.pdf
|
|
...
I already have about 8 directories. 我已经有大约8个目录。 I need to delete all pdfs in the user
directory and it's sub-direcotries. 我需要删除user
目录及其子目录下的所有pdf文件。
I use the following to delete old db backups: 我使用以下命令删除旧的数据库备份:
00 06 * * * find /path/to/backups/* -mtime +14 -delete
Some parts are quite obvious. 有些部分很明显。 +14
would become +7
, /*
would be /*.pdf
+14
将变成+7
, /*
将是/*.pdf
00 06 * * * find /path/to/users/*.pdf -mtime +7 -delete
But what about the sub-directories? 但是子目录呢?
Cheers 干杯
Replace: 更换:
00 06 * * * find /path/to/users/*.pdf -mtime +7 -delete
With: 带有:
00 06 * * * find /path/to/users/ -type f -iname '*.pdf' -mtime +7 -delete
Notes: 笔记:
find
will automatically recurse through subdirectories. find
将自动通过子目录递归。 We just need to tell it to start at /path/to/users/
and it will look through all of users
subdirectories recursively. 我们只需要告诉它从/path/to/users/
开始,它将以递归方式浏览所有users
子目录。
To limit the search to regular files, we add -type f
. 为了将搜索限制为常规文件,我们添加-type f
。
To limit the search to files whose name end in .pdf
, we add -iname '*.pdf'
(using -iname makes the match case-insensitive, which is usually a good idea) . 为了将搜索范围限制为名称以.pdf
结尾的文件,我们添加了-iname '*.pdf'
(使用-iname可使匹配不区分大小写,通常是个好主意) 。
Before creating the above cronjob, try: 在创建上述cronjob之前,请尝试:
find /path/to/users/ -type f -name '*.pdf' -mtime +7
This will show you what files would be deleted. 这将向您显示将删除哪些文件。 If you are satisfied that this list is what you want, then you run it again with -delete
or create the cronjob. 如果您对所需的列表感到满意,则可以使用-delete
再次运行它或创建cronjob。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.