需要删除一个月前的所有子目录。但前三个月的本月最后一天的数据应被忽略。
其data representation
情况如下:
bkp_01102014 bkp_04102014 bkp_07102014 bkp_11102014 bkp_15112014
...................
...................
bkp_24112014 bkp_27112014 bkp_30062014 bkp_31072 bkp_20092014
如何使用find
或任何其他命令自动执行此操作?
答案1
我认为你不需要重命名这些文件。您可以即时转换文件名(第一个 sed),将它们与日期进行比较(awk)并将匹配的文件名转换回来(第二个 sed)。
find parent/directory -maxdepth 1 -type d -name 'bkp_*' | \
sed 's#parent/directory/bkp_\(..\)\(..\)\(....\)#\3\2\1#' | \
awk -v date=$(date --date='3 months ago' +%Y%m%d) '$0<$date{print $0}' | \
sed 's#\(....\)\(..\)\(..\)#parent/directory/bkp_\3\2\1#' | \
xargs rm -r
您应该首先在没有 xargs rm 部分的情况下测试它!
答案2
尝试编写 Bash 脚本。请检查它是否可以帮助您。
#!/bin/bash
NOW=`date +%s`
last_day()
{
case $MM in
01|03|05|07|08|10|12 )
echo "31" ;;
04|06|09|11 )
echo "30" ;;
02 )
echo "28" ;;
esac
}
for file in `ls -1 bkp*`
do
# echo $file
DATE=`echo $file | tr -cd [0-9]` # Extract Day of the Month from file name
YY=`echo $DATE | cut -c5-8` # Extract Year from file name
MM=`echo $DATE | cut -c3-4` # Extract Month of Year fro file name
DD=`echo $DATE | cut -c1-2`
FDATE=`echo ${YY}${MM}${DD}` # Re-arrange the date
FDATE=`date +%s -d $FDATE` # Date in terms of seconds
# echo "FILEDATE= $FDATE"
DIFF=`echo "$NOW - $FDATE" | bc` # Difference between NOW and FILEDATE in Seconds
# echo "DIFF FROM NOW= $DIFF"
DIFFDAYS=`echo "$DIFF / 86400" | bc` # Difference in terms of DAYS
DIFFMONTHS=`echo "$DIFFDAYS / 30" | bc` # Difference in terms of MONTHS
# echo "DIFF IN DAYS= $DIFFDAYS"
# echo "DIFF IN MONTHS = $DIFFMONTHS"
LASTDAY=$(last_day $MM) # To determine whether it is a last day of month
# echo $LASTDAY
if [ $DIFFMONTHS -ge 1 ]
then
if [ $DD -eq $LASTDAY -a $DIFFMONTHS -ge 4 ]
then
rm -rf $file
else
rm -rf $file
fi
fi
done
测试输出:
执行脚本之前:
$ ls
bkp_20082013 bkp_20082014 bkp_20112014
bkp_20071989 bkp_20092014 bkp_30112014
bkp_20072014 bkp_20102014 bkp_31102014
执行脚本后:
bkp_20112014 bkp_30112014