删除目录中的所有文件,但符合特定条件的列表除外

时间:2012-09-17 11:19:16

标签: linux bash delete-file rm

我需要自动清理只保存备份文件的基于Linux的FTP服务器。

在我们的“\ var \ DATA”目录中是目录的集合。此处用于备份的任何目录都以“DEV”开头。在每个“DEVxxx *”目录中都有实际的备份文件,以及在这些设备上维护过程中可能需要的任何用户文件。

我们只想保留以下文件 - 这些“DEVxxx *”目录中的其他内容将被删除:

The newest two backups:  ls -t1 | grep -m2 ^[[:digit:]{6}_Config]  
The newest backup done on the first of the month:  ls -t1 | grep -m1 ^[[:digit:]{4}01_Config] 
Any file that was modified less than 30 days ago:  find -mtime -30  
Our good configuration file:  ls verification_cfg

任何与上述内容不符的内容都应删除。

我们如何编写此脚本?

我猜测BASH脚本可以做到这一点,我们可以创建一个cron作业来每天运行来执行任务。

2 个答案:

答案 0 :(得分:1)

或许这样的事情?

{ ls -t1 | grep -m2 ^[[:digit:]{6}_Config] ;
  ls -t1 | grep -m1 ^[[:digit:]{4}01_Config] ;
  find -mtime -30 ;
  ls -1 verification_cfg ;
} | rsync -a --exclude=* --include-from=- /var/DATA/ /var/DATA.bak/
rm -rf /var/DATA
mv /var/DATA.bak /var/DATA

答案 1 :(得分:0)

对于它的价值,这是我为完成任务而创建的bash脚本。欢迎提出意见。

#!/bin/bash

# This script follows these rules:
#
#  - Only process directories beginning with "DEV"
#  - Do not process directories within the device directory
#  - Keep files that match the following criteria:
#     - Keep the two newest automated backups
#     - Keep the six newest automated backups generated on the first of the month
#     - Keep any file that is less than 30 days old
#     - Keep the file "verification_cfg"
#
#  - An automated backup file is identified as six digits, followed by "_Config"
#    e.g.  20120329_Config


# Remember the current directory
CurDir=`pwd`

# FTP home directory
DatDir='/var/DATA/'
cd $DatDir

# Only process directories beginning with "DEV"
for i in `find . -type d -maxdepth 1 | egrep '\.\/DEV' | sort` ; do
 cd $DatDir

 echo Doing "$i"
 cd $i

 # Set the GROUP EXECUTE bit on all files
 find . -type f -exec chmod g+x {} \;

 # Find the two newest automated config backups
 for j in `ls -t1 | egrep -m2 ^[0-9]{8}_Config$` ; do
  chmod g-x $j
 done

 # Find the six newest automated config backups generated on the first of the month
 for j in `ls -t1 | egrep -m6 ^[0-9]{6}01_Config$` ; do
  chmod g-x $j
 done

 # Find all files that are less than 30 days old
 for j in `find -mtime -30 -type f` ; do
  chmod g-x $j
 done

 # Find the "verification_cfg" file
 for j in `find -name verification_cfg` ; do
  chmod g-x $j
 done

 # Remove any files that still have the GROUP EXECUTE bit set
 find . -type f -perm -g=x -exec rm -f {} \;

done

# Back to the users current directory
cd $CurDir