我使用了以下命令:
aws s3 ls s3://mybucket/mydir --recursive > bigfile
生成的文件太大(9.5MB),无法方便地使用,因为我需要仔细查看我正在寻找的信息。
我真正需要的是三层以下的信息。是否可以调整此命令,以便我只向下递归 N 个级别,而不是一直向下递归每个目录?我没有看到任何类似
-maxdepth
的 S3 CLI ls 命令
更新:这是我最终用来获取所需信息的命令,尽管我对此不满意。当我只想要 40 个左右的唯一值时,它仍然给了我 77000 个结果,但它足够短,可以移植到 Excel 中,并通过文本到列进行缩减并删除重复项。
aws s3 ls s3://mybucket/mydir --human-readable --summarize --recursive | egrep '*_keytext_*' | tr -s ' ' | cut -d' ' -f5 >smallerfile
虽然接受的答案完全正确,但拥有此功能仍然非常有用,aws-cli 上的错误报告证明了这一点(https://github.com/aws/aws-cli/issues/2683) .
我使用
bash
脚本和 awk
脚本解决了这个问题。 bash 脚本获取单个级别,awk
脚本解析输出并将递归调用 bash
脚本以获得下一个级别。
#!/bin/bash
# Save as ./s3-tree.sh
bucket=$1; max_depth=$2; path=${3:-}; depth=${4:-1};
[ $depth -gt $max_depth ] || \
aws s3 ls "s3://$bucket/$path" | \
awk -v bucket="$bucket" -v path="$path" -v depth="$depth" -v max_depth="$max_depth" -f s3-tree.awk
#!/bin/awk
# Save as: ./s3-tree.awk
BEGIN { FIELDWIDTHS = "10 1 8 1 10 1 600" }
$5 == 0 { next } # Ignore zero-size files
{ print $1 " " $3 " " $5 " " path $7 }
$5 == " PRE" && depth <= max_depth { system("./s3-tree.sh " bucket " " max_depth " " path $7 " " depth+1); next }
调用为:
./s3-tree.sh <my-bucket-name> <max-depth> [<starting-path>]
分享并享受!
Amazon S3 没有“级别”的概念。它是一个平面存储系统,路径是对象名称(Key)的一部分。然而,某些 API 调用支持指定
Prefix
的功能,其操作方式就像在特定目录中查找一样。
使用
aws s3 ls
的替代方法是使用 Amazon S3 Inventory,它可以提供列出存储桶内容的每日 CSV 文件。
虽然它不是纯粹的 shell+awscli 解决方法,但 Python 包
s3fs
具有相当快的递归通配函数,并且 s3fs 相当成熟
例如
# pip install s3fs
import s3fs
s3 = s3fs.S3FileSystem()
s3.glob(f'{BUCKET}/*/*findme*')
# much slower of course
s3.glob(f'{BUCKET}/**/*findme*')
# returns
'''
['BUCKET/checkpoints/findme',
'BUCKET/checkpoints/temp_findme_other',
'BUCKET/tables/findme',
'BUCKET/tables/temp_findme_other']
'''