【问题标题】:Find and delete old files excluding some subdirectories查找和删除旧文件,不包括某些子目录
【发布时间】:2013-06-11 14:38:51
【问题描述】:

我一直在寻找一段时间,但似乎无法得到一个简洁的解决方案。我正在尝试删除旧文件,但不包括一些子目录(通过 parm 传递)及其子子目录。

我遇到的问题是,当 subdirectory_name 本身早于通知的持续时间(也通过 parm 传递)时,find 命令将 subdirectory_name 包含在查找列表中。实际上,remove 无法删除这些子目录,因为rm 命令的默认选项是f

这里是脚本生成的查找命令:

find /directory/ \( -type f -name '*' -o -type d \
    -name subdirectory1 -prune -o -type d -name directory3 \
    -prune -o -type d -name subdirectory2 -prune -o \
    -type d -name subdirectory3 -prune \) -mtime +60 \
    -exec rm {} \; -print 

这里是文件列表(以及 find 命令带来的子目录)

/directory/subdirectory1  ==> this is a subdreictory name and I'd like to not be included   
/directory/subdirectory2  ==> this is a subdreictory name and I'd like to not be included      
/directory/subdirectory3  ==> this is a subdreictory name and I'd like to not be included        
/directory/subdirectory51/file51               
/directory/file1 with spaces 

除此之外——脚本工作正常,不带(排除)以下 3 个子目录下的文件: subdirectory1subdirectory2subdirectory3

谢谢。

【问题讨论】:

    标签: shell unix directory


    【解决方案1】:

    以下命令将仅删除超过 1 天的文件。 您可以排除目录,如下例所示,目录 test1 和 test2 将被排除。

    find /path/ -mtime +60 -type d \( -path ./test1 -o -path ./test2 \) -prune -o -type f -print0 | xargs -0 rm -f 
    

    虽然建议使用 -print 查看将要删除的内容

    find /path/ -mtime +60 -type d \( -path ./test1 -o -path ./test2 \) -prune -o -type f -print
    

    【讨论】:

      【解决方案2】:
      find /directory/ -type d \(
          -name subdirectory1 -o \
          -name subdirectory2 -o \
          -name subdirectory3 \) -prune -o \
          -type f -mtime +60 -print -exec rm -f {} +
      

      请注意,AND 运算符(-a,如果未指定,则在两个谓词之间隐含)优先于 OR 运算符(-o)。所以上面是这样的:

      find /directory/ \( -type  d -a \(
          -name subdirectory1 -o \
          -name subdirectory2 -o \
          -name subdirectory3 \) -a -prune \) -o \
          \( -type f -a -mtime +60 -a -print -a -exec rm -f {} + \)
      

      请注意,每个文件名都与* 模式匹配,因此-name '*' 就像-true 一样,没有用处。

      使用+ 而不是; 运行更少的rm 命令(尽可能少,并且每个都传递几个文件以删除)。

      不要在其他人可写的目录上使用上面的代码,因为它很容易受到攻击,攻击者可以在 find 遍历目录并调用 rm 获取你的时间之间将目录更改为符号链接到另一个目录删除文件系统上的任何文件。如果您的find 支持它们,可以通过将-exec part 更改为-delete-execdir rm -f {} \; 来缓解它们。

      如果要排除特定的 subdirectory1 而不是名称为 subdirectory1 的任何目录,另请参阅 -path 谓词。

      【讨论】:

      • 这个版本有效:find /directory/ ( -type d -a ( -name subdirectory1 -o -name subdirectory2 -o -name subdirectory3 ) -a -prune ) -o ( -type f -a -mtime +60 -a -print )
      • @user2487539, -path 是 POSIX,但它是 POSIX 规范 (2008) 中相对较新的补充。不过,它已经在许多 find 实现中出现了一段时间。
      • 还有一个问题:是否可以在删除文件时打印文件的“更改日期”?谢谢!
      • @user2487539,添加 -exec ls -ld {} \; 表示上次修改时间,-exec ls -lcd {} \; 表示上次 inode 更改时间。
      猜你喜欢
      • 2017-10-08
      • 1970-01-01
      • 2013-07-31
      • 2017-05-28
      • 1970-01-01
      • 2014-12-13
      • 1970-01-01
      • 1970-01-01
      • 2017-05-06
      相关资源
      最近更新 更多