删除与时间模式匹配的目录中的所有文件

时间:2016-11-04 12:18:24

标签: shell

我使用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

3 个答案:

答案 0 :(得分:1)

## Get roughly the same area as in the Google map bbox <- c(left=-1.88, bottom=55.625, right=-1.74, top=55.685) ## Broken in ggmap 2.6.1, try GitHub version (which may have other problems) foo3 <- get_map(location = bbox, zoom = 13, crop = FALSE, source = "stamen", maptype = "terrain", force = FALSE) ## Compare the two map sources / types dev.new() print(ggmap(foo2)) dev.new() print(ggmap(foo3)) 您可以打印目录中除最后3个文件之外的所有文件。 将此输出传递到ls -lrt | head -n -3 | awk '{print $9},您将获得所需的结果。

答案 1 :(得分:0)

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

@Component
public class ResponseInterceptor extends HandlerInterceptorAdapter {

    @Override
    public void postHandle(final HttpServletRequest request, final HttpServletResponse response, final Object handler,
            final ModelAndView modelAndView) throws IOException {
         if (response.getContentType() == null || response.getContentType().equals("")) {
            response.setContentType("application/json");
         }
     }
}

也用这个;

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

答案 2 :(得分: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

如果在您的目录上运行,则会产生如下输出:

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

所以现在只需要用echo更有意义的内容替换那些rm

相关问题