简体   繁体   English

从 S3 存储桶中的文件夹中删除文件

[英]Delete files from folder in S3 bucket

I have an AWS S3 bucket test-bucket with a data folder.我有一个带有data文件夹的 AWS S3 存储桶test-bucket The data folder will have multiple files.数据文件夹将有多个文件。

I am able to delete the files in the S3 bucket.我能够删除 S3 存储桶中的文件。 But what I want is to delete the files in the data folder without deleting the folder.但是我想要的是在不删除文件夹的情况下删除data文件夹中的文件。

I tried the following:我尝试了以下内容:

aws s3 rm  s3://test-bucket/data/*

Also checked using --recursive option, but that does not work.还使用--recursive选项进行了检查,但这不起作用。

Is there a way I can delete the files in the folder using AWS CLI?有没有一种方法可以使用 AWS CLI 删除文件夹中的文件?

以下 aws cli 命令有效:

aws s3 rm s3://test-bucket --recursive --exclude="*" --include="data/*.*"

you can do it using aws cli : https://aws.amazon.com/cli/ and some unix command.您可以使用 aws cli 来完成: https ://aws.amazon.com/cli/ 和一些 unix 命令。

this aws cli commands should work:这个 aws cli 命令应该可以工作:

aws s3 rm s3://<your_bucket_name> --exclude "*" --include "<your_regex>"

if you want to include sub-folders you should add the flag --recursive如果要包含子文件夹,则应添加标志--recursive

or with unix commands:或使用 unix 命令:

aws s3 ls s3://<your_bucket_name>/ | awk '{print $4}' | xargs -I%  <your_os_shell>   -c 'aws s3 rm s3:// <your_bucket_name>/% $1'

explanation: list all files on the bucket --pipe--> get the 4th parameter(its the file name) --pipe--> run delete script with aws cli解释:列出存储桶上的所有文件--pipe-->获取第 4 个参数(它的文件名) --pipe-->使用 aws cli 运行删除脚本

aws s3 rm s3://bucket/folder1/folder2/ --recursive --dryrun

从我尝试时看到的情况来看,在末尾添加斜杠意味着在文件夹 2 下方删除,不包括文件夹 2。

We can remove all files including sub-folders as well from AWS-S3-BUCKET In Node.js by using the below function.我们可以使用以下 function 从 Node.js 中的 AWS-S3-BUCKET 中删除包括子文件夹在内的所有文件。

the same command can be used in AWS-CLI by configuring AWS in the command-line.通过在命令行中配置 AWS,可以在 AWS-CLI 中使用相同的命令。

function removeAllFilesFromBucket(){
    const S3_REGION = "eu-west-1";
    const S3_BUCKET_NAME = "sample-staging";
    let filePathBucket = S3_BUCKET_NAME+'/assets/videos';

    let awsS3ShellCommand = 'aws s3 rm s3://'+filePathBucket+' --region '+S3_REGION+' --recursive';                 
    var { exec } = require('child_process');  
    exec(awsS3ShellCommand, (err, stdout, stderr) => {
        if (err) {
            console.log('err',err);                        
            return;
        }else{
            console.log('Bucket files and sub-folders Deleted successfully !!!'); 
            console.log(`stdout: ${stdout}`);
            console.log(`stderr: ${stderr}`); 
        }
    });  
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM