6

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}'` 

2 Answers 2

12

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Actually you can reverse the order by wrapping the 'sort_by' function with the reverse function, negating the need to "hack" it with a negative index. E.g. 'reverse(sort_by(Contents, &LastModified))'
-3

Use: sort -r for ascending order

From the manpage for sort

 -r, --reverse reverse the result of comparisons 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.