2016-11-04 70 views
-2

我正在使用cron每天备份一个重要的文件夹。该文件夹名称将与当前日期一起存储。删除与时间模式匹配的目录中的所有文件

现在我的要求是我只需要保留当天和最后两天的备份。

即我只想保留:

  • test_2016-11-04.tgz
  • test_2016-11-03.tgz
  • test_2016-11-02.tgz

剩余文件夹必须自动删除。请让我们知道如何在shell脚本中。

下面是我的备份文件夹结构。

test_2016-10-30.tgz test_2016-11-01.tgz test_2016-11-03.tgz 
test_2016-10-31.tgz test_2016-11-02.tgz test_2016-11-04.tgz 

回答

0

你可以附加备份脚本的结尾;

find ./backupFolder -name "test_*.tgz" -mtime +3 -type f -delete 

也使用此;

ls -1 test_*.tgz | sort -r | awk 'NR > 3 { print }' | xargs -d '\n' rm -f -- 
0

生成的文件数组你想保留:

names=() 
for d in {0..2}; do 
    names+=("test_"$(date -d"$d days ago" "+%Y-%m-%d")".tgz") 
done 

,使它看起来像这样:

$ printf "%s\n" "${names[@]}" 
test_2016-11-04.tgz 
test_2016-11-03.tgz 
test_2016-11-02.tgz 

然后通过文件循环和keep those that are not in the array

for file in test_*.tgz; do 
    [[ ! ${names[*]} =~ "$file" ]] && echo "remove $file" || echo "keep $file" 
done 

如果在你的导演Y,这将导致对等的输出:

remove test_2016-10-30.tgz 
remove test_2016-10-31.tgz 
remove test_2016-11-01.tgz 
keep test_2016-11-02.tgz 
keep test_2016-11-03.tgz 
keep test_2016-11-04.tgz 

所以现在它只是一个问题或更有意义的事情像rm取代那些echo

+0

感谢您的回复。它帮助我很多 – iamarunk

1

With ls -lrt | head -n -3 | awk '{print $9} 您可以打印除目录中最后3个文件以外的所有文件。 将此输出传递到rm您将获得所需的结果。

+1

值得一读:[为什么*不*解析'ls'?](http://unix.stackexchange.com/q/128985/40596) – fedorqui

相关问题