【问题标题】:How to clean up folders efficiently using shell script如何使用 shell 脚本有效地清理文件夹
【发布时间】:2017-03-29 14:56:30
【问题描述】:

我正在使用包含各种文件夹的目录结构。其中一些每天都会创建新文件。

我已经创建了一些程序来清理目录,但我想使用一个 shell 脚本来提高效率。

因此,我想在每个需要清理的文件夹中存储一个“archiving.properties”文件。属性文件应包含以下变量

file_pattern="*.xml"
days_to_keep=2

现在我的清理程序应该:

  1. 查找所有属性文件
  2. 删除与文件名模式 (file_pattern) 匹配且早于属性文件所在目录中定义的天数 (days_to_keep) 的所有文件。

所以我的问题是如何以最有效的方式做到这一点?

find . -type f -name "archiving.properties"  -print
find . -type f -name "<file_pattern>"  -mtime +<days_to_keep> -delete

目前我正在单个文件夹中尝试以下操作。它正确打印出命令,但没有执行。

#!/bin/bash
. archiving.properties
find . -type f -name "*.xml"  -mtime +1 -exec rm -rf {} \;
echo "    find . -type f -name \"${file_pattern}\"  -mtime +${days_to_keep} -exec rm -rf {} \;" 


Result is:    find . -type f -name "*.xml"  -mtime +1 -exec rm -rf {} \;

提前感谢您的帮助。

【问题讨论】:

  • 到目前为止你尝试过什么?暂时忘记对整个目录树的操作;如果您有一个包含您提议的 archive.properties 文件的目录,您是否考虑过如何处理它?

标签: linux shell scripting


【解决方案1】:

我得到了最终结果

echo "start deleting files in " $(pwd) " ... "

#filename of the properties
properties="clean_up.properties"

#find all properties files
for prop in $(find . -type f -name $properties);do
        #init variables
        file_pattern="*._html"
        days_to_keep=14

        #load the variables from the properties file
        . "$prop"

        #define the folder of the properties file
        folder=${prop%?$properties}

        #remove all files matching the parameters in the folder where the properties were found
        echo ">>>   find $folder -type f -name \"${file_pattern}\" -mtime +${days_to_keep} -exec rm -f {} \;"
                    find $folder -type f -name "${file_pattern}"   -mtime +${days_to_keep} -exec rm -f {} \;
done
echo "... done"

【讨论】:

    猜你喜欢
    • 2011-10-20
    • 2015-11-02
    • 1970-01-01
    • 1970-01-01
    • 2021-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-08
    相关资源
    最近更新 更多