Explore Courses Blog Tutorials Interview Questions
0 votes
1 view
in AWS by (19.1k points)

I could fetch the recent 5 files added or updated by:

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

Now how do I keep these files and delete all other?

1 Answer

0 votes
by (44.3k points)

There are 2 options for you to use. 

  1. The first option requires the names of the last 5 files
  2. Second option is a shell script which you cna run to do the same

The first option is this:

Use --exclude option with the aws s3 rm command as show below:

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

Use this script to get all files but the last 5 uploaded files:

aws s3 ls s3://bucketname/ --recursive | sort | head -n -5 | while read -r line ; do

    echo "Removing ${line}"

    aws s3 rm s3://bucketname/${line}


line - The number of lines (objects) to be removed

bucketname - provide the name of the bucket with the objects

Related questions

Want to get 50% Hike on your Salary?

Learn how we helped 50,000+ professionals like you !

+1 vote
1 answer
0 votes
1 answer
asked Feb 7, 2020 in AWS by yuvraj (19.1k points)
0 votes
1 answer
asked Dec 16, 2020 in AWS by devin (5.6k points)

Browse Categories