shell AWS S3无法正确获取包含空格的对象键

67up9zun  于 12个月前  发布在  Shell
关注(0)|答案(1)|浏览(112)

我试图重置我的S3存储桶中所有文件的Content-Type,而内容类型的事情正在工作,我遇到了一些文件夹在我的存储桶中的问题-这显然是由于文件夹名称中的空格。
我有这个剧本

#!/bin/bash

S3_BUCKET="mytestbucket"

# List all objects in the S3 bucket recursively
aws s3 ls "s3://${S3_BUCKET}/ Jon Doe/" --recursive | while IFS= read -r line
do
    # OBJECT_KEY=$(echo "$line" | awk '{print $4}')
    echo "$line"
    OBJECT_KEY=$(echo "$line" | awk '{print $4}')
    echo "$OBJECT_KEY"
    FILE_EXTENSION="${OBJECT_KEY##*.}"  # Extract the file extension

    # Map file extensions to content types
    case "$FILE_EXTENSION" in
        pdf)
            CONTENT_TYPE="application/pdf"
            ;;
        jpg|jpeg)
            CONTENT_TYPE="image/jpeg"
            ;;
        png)
            CONTENT_TYPE="image/png"
            ;;
        mp4)
            CONTENT_TYPE="video/mp4"
            ;;
        wmv)
            CONTENT_TYPE="video/x-ms-wmv"
            ;;
        txt)
            CONTENT_TYPE="text/plain"
            ;;
        *)
            # Default to a generic binary type if the extension is not recognized
            CONTENT_TYPE="application/octet-stream"
            ;;
    esac

    # Update the Content-Type metadata for the object
    aws s3 cp "s3://${S3_BUCKET}/${OBJECT_KEY}" "s3://${S3_BUCKET}/${OBJECT_KEY}" --content-type "${CONTENT_TYPE}"
    # Print a message indicating that the operation is complete for this object
    echo "s3://${S3_BUCKET}/${OBJECT_KEY}"
    echo "Updated Content-Type for $OBJECT_KEY to $CONTENT_TYPE" 
done

我希望$OBLOG_KEY是类似于s3://mytestbucket/ Jon Doe/filename.jpg的东西,例如,但我最终得到了s3://mytestbucket/Jon
此脚本完全适用于不包含任何空格的文件夹路径。我已经尝试了几种不同的代码,例如从代码中删除IFS=,然后还有类似这样的东西。

# Extract the object key (filename) from the line
OBJECT_KEY=$(echo "$line" | sed 's/.*\(s3:\/\/.*\)/\1/')

# Skip empty lines
if [ -z "$OBJECT_KEY" ]; then
    continue
fi

# Trim leading and trailing spaces
OBJECT_KEY=$(echo "$OBJECT_KEY" | xargs)
echo "$OBJECT_KEY"

似乎什么都不管用。
任何帮助都是感激不尽的。谢谢你,谢谢

owfi6suc

owfi6suc1#

我能够通过使用CLI的不同API来解决这个问题,它只选择对象键,而不是打印整行数据,然后尝试从中提取对象键,因为我的文件夹中有空格,即使在名称的开头也很难这样做。
我的新方法是使用s3apilist-objects,它只返回我所需要的对象键。

#!/bin/bash

# List all objects in the S3 bucket recursively
aws s3api list-objects-v2 --bucket mytestbucket --query "Contents[].Key" --output text | tr '\t' '\n' | while IFS= read -r line
do
...
...
... rest of the code

相关问题