Get the most recent object from S3 with script

Here is the code

Explanation of How it works

  1. Use AWS CLI to list the objects
  2. Sort the list by last modified time
  3. Grab the last item in the list
  4. Extract the 4th column

First, list all the S3 objects in the bucket with AWS-CLI:

By default, the list is sorted alphabetically by key. Note the first column is the last modified time.

Then piping the list into sort will reorder them by the first column (last modified time),

After that, use tail -n 1 to select the last row of the now time sorted list.

TIP: tail -n 1 gives the very latest.
However you may want a group of latest (like 3) from which to select a specific name.

tail -n 3 selects the last 3 rows

In the past, I have used tail -n 6 to get the latest 6 objects and then looked for a specific filename within those latest 6 files.

Since the name is what is wanted, use awk ‘{print $4}’ to extract the fourth column.

Then you can copy it to some directory if you like:

Leave a Reply

Your email address will not be published. Required fields are marked *