Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Rename files en masse on Amazon S3
require "aws-sdk"
s3 = Aws::S3::Client.new(region: ENV.fetch("region", "us-west-2"))
objects = []
start_after = nil
loop do
resp = s3.list_objects_v2(
bucket: ENV.fetch("bucket"),
max_keys: ENV.fetch("max_keys", 1000).to_i,
start_after: start_after,
prefix: ENV["prefix"]
)
objects += resp.contents
start_after = resp.contents.last.key
break if resp.is_truncated != true
end
objects.each do |object|
key_parts = object.key.split("/")
if key_parts.size > 1
s3.copy_object(
bucket: ENV.fetch("bucket"),
copy_source: ENV.fetch("bucket") + "/" + object.key,
key: key_parts.join("-")
)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment