【问题标题】:How do I delete all except the latest 5 recently updated/new files from AWS s3?如何从 AWS s3 中删除除最新的 5 个最近更新/新文件之外的所有文件?
【发布时间】:2017-05-14 11:17:40
【问题描述】:

我可以使用以下命令从 AWS S3 获取最后五个更新的文件

aws s3 ls s3://somebucket/ --recursive | sort | tail -n 5 | awk '{print $4}'

现在我需要删除 AWS S3 中的所有文件,除了从 AWS 中的上述命令获取的最后 5 个文件。

假设命令获取1.txt,2.txt,3.txt,4.txt,5.txt。我需要从 AWS S3 中删除除 1.txt,2.txt,3.txt,4.txt,and 5.txt 之外的所有内容。

【问题讨论】:

标签: linux shell amazon-web-services amazon-s3 aws-cli


【解决方案1】:

使用带有多个 --exclude 选项的 AWS s3 rm 命令(我假设最后 5 个文件不属于某个模式)

aws s3 rm s3://somebucket/ --recursive --exclude "somebucket/1.txt" --exclude "somebucket/2.txt" --exclude "somebucket/3.txt" --exclude "somebucket/4.txt" --exclude "somebucket/5.txt"

注意:请务必使用--dryrun 选项进行尝试,在实际删除文件之前确认要删除的文件不包括这 5 个文件。

【讨论】:

    【解决方案2】:

    head 中使用负数来获取除最后n 之外的所有行:

    aws s3 ls s3://somebucket/ --recursive | sort | head -n -5 | while read -r line ; do
        echo "Removing ${line}"
        aws s3 rm s3://somebucket/${line}
    done
    

    【讨论】:

      【解决方案3】:

      短篇小说:基于@bcattle answser,适用于 AWS CLI 2:

      aws s3 ls s3://[BUCKER_NAME] --recursive | awk 'NF>1{print $4}' | grep . | sort | head -n -5 | while read -r line ; do
          echo "Removing ${line}"
          aws s3 rm s3://[BUCKER_NAME]/${line}
      done
      

      长篇大论: aws s3 ls 在 CLI 2 文件路径下返回,但也是日期创建。我们的脚本中不会出现这种行为,因为我们只希望文件路径与存储桶 uri 连接。

      【讨论】:

        猜你喜欢
        • 2016-09-25
        • 1970-01-01
        • 1970-01-01
        • 2023-03-11
        • 1970-01-01
        • 2015-03-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多