根据命名模式删除文件夹

时间:2014-08-26 05:56:57

标签: bash shell directory-structure

我有400个文件夹的列表,其格式如下:

backup_01_01_2013/
backup_01_02_2013/
backup_01_03_2013/
...
backup_08_25_2014/

每天通过cron作业创建一个新文件夹。

我想删除所有文件夹,除非:

  • 保留30个最新文件夹
  • 保持每个月的第一天

如何在Linux中使用Bash删除所有不必要的文件夹?

2 个答案:

答案 0 :(得分:1)

所以,假设他们都在同一个目录中。

我指出我测试了这个脚本的部分内容,但不是全部,所以你可能想要在实际运行之前做一些修改/测试 - 以免你最终得到所有目录已删除。

# Find the date 30 days ago.
recent_dirs=`date -d "-30 days" +%d-%m-%Y`
rec_month=`echo "${recent_dirs}" | cut -d '-' -f2`
rec_day=`echo "${recent_dirs}" | cut -d '-' -f1`
rec_month=`echo "${recent_dirs}" | cut -d '-' -f3`

# Go to your "home" directory for the directories.
cd /path/to/home/directory

for i in *; do
    # Check to see if the element is a directory.
    if [ -d "${i}" ]; then
        echo "Processing directory - ${i} ... "
        # Determine the date information for the directory.
        cur_month=`cat "${i}" | cut -d '_' -f1`
        cur_day=`cat "${i}" | cut -d '_' -f2`

        # Keep all directories from the first of the month.
        if [ "${first_day}" -eq "01" ]; then continue; fi

        # Keep all directories from the current month and current year.
        if [ "${cur_month}" -eq "${rec_month}" ]; then
            if [ "${cur_year}" -eq "${rec_year}" ]; then continue; fi
        fi

        # Keep all directories from last month, but newer than today's DAY.  I'm not 
        #  a pro at bash arithmetic, so you might have to goof with the subshell 
        #  math to get it to work quite right.
        if [ "${cur_month} -eq $(( expr $rec_month - 1 )) ]; then
            if [ "${cur_day}" -gt "${rec_day}" ]; then continue; fi
        fi

        # So at this point, I think we've dealt with everything, except the case where
        #  the current month is January, and so you're trying to save December's 
        #  directories from last year.  I think this handles it.

        if [ "${rec_month}" -eq "01" ]; then
            if [ "${cur_month} -eq "12" ]; then
                if [ "${cur_year}" -eq $(( expr ${rec_year} - 1 )) ]; then continue; fi
            fi
        fi

        # If we haven't stopped processing the directory by now, it's time 
        #   remove our directory.
        rm -fr "${i}"
     else
        echo "Skipping non-directory "${i}"...
 do

退出1

这不会做的事情是处理31天的月份,所以你可能会在很多情况下最终保存了31个目录,而不是30个。我得到的印象是你正在尝试虽然做了清理,而不是严格的合规程序......

答案 1 :(得分:0)

快速&脏 - 尝试'ls -ltr'结合tail -30得到除了30.运行for循环和rm -rf