【问题标题】:Delete all files in a directory matching a time pattern删除与时间模式匹配的目录中的所有文件
【发布时间】:2017-03-18 06:38:52
【问题描述】:

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

【问题讨论】:

    标签: shell


    【解决方案1】:

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

    【讨论】:

    【解决方案2】:

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

    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 --
    

    【讨论】:

      【解决方案3】:

      在要保留的文件上生成一个数组:

      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

      【讨论】:

      • 感谢您的回复。它对我帮助很大
      猜你喜欢
      • 2021-11-24
      • 2015-04-25
      • 2016-03-08
      • 1970-01-01
      • 1970-01-01
      • 2021-05-07
      • 1970-01-01
      • 2014-06-28
      • 1970-01-01
      相关资源
      最近更新 更多