kumar
kumar

Reputation: 9387

How to sort ascending order by last modified date for s3 using aws cli

Below code sort by desc. How do I have it sort by ascending?

KEY=`aws s3 ls $BUCKET --recursive | sort | tail -n 1 | awk '{print $4}'`

Upvotes: 4

Views: 15964

Answers (2)

Matt
Matt

Reputation: 1

Use: sort -r for ascending order

From the manpage for sort

   -r, --reverse
          reverse the result of comparisons

Upvotes: -3

John Rotenstein
John Rotenstein

Reputation: 269111

It appears that you wish to obtain the Key of the most recently modified object in the Amazon S3 bucket.

For that, you can use:

aws s3api list-objects --bucket bucketname --query 'sort_by(Contents, &LastModified)[-1].Key' --output text

The AWS CLI --query parameter is highly capable. It uses JMESPath, which can do most required manipulations without needing to pipe data.

The aws s3api list-objects command provides information in specific fields, rather than the aws s3 ls command which is simply text output.

The above might not work as expected if there are more than 1000 objects in the bucket, since results are returned in batches of 1000.

Upvotes: 11

Related Questions