How to rename files and folder in Amazon S3?

后端 未结 19 2195
暖寄归人
暖寄归人 2020-11-28 03:01

Is there any function to rename files and folders in Amazon S3? Any related suggestions are also welcome.

相关标签:
19条回答
  • 2020-11-28 03:33

    rename all the *.csv.err files in the <<bucket>>/landing dir into *.csv files with s3cmd

     export aws_profile='foo-bar-aws-profile'
     while read -r f ; do tgt_fle=$(echo $f|perl -ne 's/^(.*).csv.err/$1.csv/g;print'); \
            echo s3cmd -c ~/.aws/s3cmd/$aws_profile.s3cfg mv $f $tgt_fle; \
     done < <(s3cmd -r -c ~/.aws/s3cmd/$aws_profile.s3cfg ls --acl-public --guess-mime-type \
            s3://$bucket | grep -i landing | grep csv.err | cut -d" " -f5)
    
    0 讨论(0)
  • 2020-11-28 03:34

    This works for renaming the file in the same folder

    aws s3  mv s3://bucketname/folder_name1/test_original.csv s3://bucket/folder_name1/test_renamed.csv
    
    0 讨论(0)
  • 2020-11-28 03:36

    Below is the code example to rename file on s3. My file was part-000* because of spark o/p file, then i copy it to another file name on same location and delete the part-000*:

    import boto3
    client = boto3.client('s3')
    response = client.list_objects(
    Bucket='lsph',
    MaxKeys=10,
    Prefix='03curated/DIM_DEMOGRAPHIC/',
    Delimiter='/'
    )
    name = response["Contents"][0]["Key"]
    copy_source = {'Bucket': 'lsph', 'Key': name}
    client.copy_object(Bucket='lsph', CopySource=copy_source, 
    Key='03curated/DIM_DEMOGRAPHIC/'+'DIM_DEMOGRAPHIC.json')
    client.delete_object(Bucket='lsph', Key=name)
    
    0 讨论(0)
  • 2020-11-28 03:40

    As answered by Naaz direct renaming of s3 is not possible.

    i have attached a code snippet which will copy all the contents

    code is working just add your aws access key and secret key

    here's what i did in code

    -> copy the source folder contents(nested child and folders) and pasted in the destination folder

    -> when the copying is complete, delete the source folder

    package com.bighalf.doc.amazon;
    
    import java.io.ByteArrayInputStream;
    import java.io.InputStream;
    import java.util.List;
    
    import com.amazonaws.auth.AWSCredentials;
    import com.amazonaws.auth.BasicAWSCredentials;
    import com.amazonaws.services.s3.AmazonS3;
    import com.amazonaws.services.s3.AmazonS3Client;
    import com.amazonaws.services.s3.model.CopyObjectRequest;
    import com.amazonaws.services.s3.model.ObjectMetadata;
    import com.amazonaws.services.s3.model.PutObjectRequest;
    import com.amazonaws.services.s3.model.S3ObjectSummary;
    
    public class Test {
    
    public static boolean renameAwsFolder(String bucketName,String keyName,String newName) {
        boolean result = false;
        try {
            AmazonS3 s3client = getAmazonS3ClientObject();
            List<S3ObjectSummary> fileList = s3client.listObjects(bucketName, keyName).getObjectSummaries();
            //some meta data to create empty folders start
            ObjectMetadata metadata = new ObjectMetadata();
            metadata.setContentLength(0);
            InputStream emptyContent = new ByteArrayInputStream(new byte[0]);
            //some meta data to create empty folders end
    
            //final location is the locaiton where the child folder contents of the existing folder should go
            String finalLocation = keyName.substring(0,keyName.lastIndexOf('/')+1)+newName;
            for (S3ObjectSummary file : fileList) {
                String key = file.getKey();
                //updating child folder location with the newlocation
                String destinationKeyName = key.replace(keyName,finalLocation);
                if(key.charAt(key.length()-1)=='/'){
                    //if name ends with suffix (/) means its a folders
                    PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, destinationKeyName, emptyContent, metadata);
                    s3client.putObject(putObjectRequest);
                }else{
                    //if name doesnot ends with suffix (/) means its a file
                    CopyObjectRequest copyObjRequest = new CopyObjectRequest(bucketName, 
                            file.getKey(), bucketName, destinationKeyName);
                    s3client.copyObject(copyObjRequest);
                }
            }
            boolean isFodlerDeleted = deleteFolderFromAws(bucketName, keyName);
            return isFodlerDeleted;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
    
    public static boolean deleteFolderFromAws(String bucketName, String keyName) {
        boolean result = false;
        try {
            AmazonS3 s3client = getAmazonS3ClientObject();
            //deleting folder children
            List<S3ObjectSummary> fileList = s3client.listObjects(bucketName, keyName).getObjectSummaries();
            for (S3ObjectSummary file : fileList) {
                s3client.deleteObject(bucketName, file.getKey());
            }
            //deleting actual passed folder
            s3client.deleteObject(bucketName, keyName);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
    
    public static void main(String[] args) {
        intializeAmazonObjects();
        boolean result = renameAwsFolder(bucketName, keyName, newName);
        System.out.println(result);
    }
    
    private static AWSCredentials credentials = null;
    private static AmazonS3 amazonS3Client = null;
    private static final String ACCESS_KEY = "";
    private static final String SECRET_ACCESS_KEY = "";
    private static final String bucketName = "";
    private static final String keyName = "";
    //renaming folder c to x from key name
    private static final String newName = "";
    
    public static void intializeAmazonObjects() {
        credentials = new BasicAWSCredentials(ACCESS_KEY, SECRET_ACCESS_KEY);
        amazonS3Client = new AmazonS3Client(credentials);
    }
    
    public static AmazonS3 getAmazonS3ClientObject() {
        return amazonS3Client;
    }
    

    }

    0 讨论(0)
  • 2020-11-28 03:41

    I just tested this and it works:

    aws s3 --recursive mv s3://<bucketname>/<folder_name_from> s3://<bucket>/<folder_name_to>
    
    0 讨论(0)
  • 2020-11-28 03:44

    To rename a folder (which is technically a set of objects with a common prefix as key) you can use the aws cli move command with --recursive option.

    aws s3 mv s3://bucket/old_folder s3://bucket/new_folder --recursive

    0 讨论(0)
提交回复
热议问题