linux - 使用 ls 和 find 命令删除旧文件

标签 linux bash shell

我的文件夹结构如下所示:

folder1
        ---tmp
        ---sub1
folder2
        ---tmp
        ---sub2
folder3
        ---tmp
        ---sub3
folder4
        ---tmp
        ---sub4

我想删除所有 tmp 文件夹中超过 30 天的文件。

列出所有 tmp 文件夹:

ls -d */tmp

删除所有超过 30 天的文件

find . -mtime +30 -type f -delete

我可以将这 2 个步骤合并到一个命令行中吗?

最佳答案

您可以将查找中的 . 替换为您要搜索的实际目录。

find */tmp -mtime +30 -type f -delete

如果 tmp 可以更深几层,那么您可能会感兴趣

find . -regex '.*/tmp/[^/]+' -mtime +30 -type f -delete

或类似于第一个选项,但使用双星球形表达式(通过 shopt -s globstar 启用)

find **/tmp -mtime +30 -type f -delete

* Matches any string, including the null string. When the globstar shell option is enabled, and * is used in a pathname expansion context, two adjacent *s used as a single pattern will match all files and zero or more directories and subdirectories. If followed by a /, two adjacent *s will match only directories and subdirectories.

source: man bash

注意:不过您必须小心。假设您有一个目录 folder1/tmp/foo/ 然后上面的命令(正则表达式版本除外)也会选择 folder1/tmp/foo 中的文件,这可能不需要。您可能对额外选项 -maxdepth 1

感兴趣

关于linux - 使用 ls 和 find 命令删除旧文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51440266/

相关文章:

c++ - mprotect:如何获取导致保护违规的指令?

linux - 无法将带有大括号扩展操作的字符串解析为命令

bash - 如何将字符串的项目分成两部分,一个包含以 '-D' 开头的项目?

linux - Bash:根据用户输入在本地或远程计算机上运行函数中的所有命令

linux - 如何在 Linux 系统上删除名为 ".."的文件

xml - 在 bash 脚本中提取 XML 值

Linux Ubuntu 命令

linux - 管理 Supervisord 进程 - 开机自动启动/崩溃时自动启动

linux - 如何向已使用的用户名添加递增数字

bash - OSX 将 shell 脚本与文件扩展名相关联?