s3cmd列出内容 - 仅文件名 - Perl一行命令?

3

目前我正在使用s3cmd ls s3://location/ > file.txt来获取我的s3存储桶中的内容列表并保存在txt文件中。但是以上命令会返回日期、文件大小、路径和文件名。

例如:

2011-10-18 08:52      6148   s3://location//picture_1.jpg

我只需要s3存储桶中的文件名 - 所以在上面的例子中,我只需要picture_1.jpg。 有什么建议吗?

这是否可以在初始导出后使用Perl单行来完成?


如果你还不知道,有CPAN模块可以方便地编程访问S3,例如Net::Amazon::S3。因此,你可以直接调用相关方法,而不是调用s3cmd。 - zgpmax
3个回答

5

使用awk:

s3cmd ls s3://location/ | awk '{ print $4 }' > file.txt

如果您的文件名中包含空格,请尝试使用以下方法:
s3cmd ls s3://location/ | awk '{ s = ""; for (i = 4; i <= NF; i++) s = s $i " "; print s }' > file.txt

2

File::Listing不支持该格式,因为此清单格式的设计者太愚蠢了,没有重复使用已有的格式。让我们手动解析它。

use URI;
my @ls = (
    "2011-10-18 08:52 6148 s3://location//picture_1.jpg\n",
    "2011-10-18 08:52 6148 s3://location//picture_2.jpg\n",
    "2011-10-18 08:52 6148 s3://location//picture_3.jpg\n",
);

for my $line (@ls) {
    chomp $line;
    my $basename = (URI->new((split q( ), $line)[-1])->path_segments)[-1];
}

__END__
picture_1.jpg
picture_2.jpg
picture_3.jpg

作为一行代码:
perl -mURI -lne 'print ((URI->new((split q( ), $line)[-1])->path_segments)[-1])' < input

0

我确定使用特定模块是更安全的选择,但如果数据可靠,你可以用一行代码搞定:

假设输入为:

2011-10-18 08:52 6148 s3://location//picture_1.jpg
2011-10-18 08:52 6148 s3://location//picture_2.jpg
2011-10-18 08:52 6148 s3://location//picture_3.jpg
...

一行代码:

perl -lnwe 'print for m#(?<=//)([^/]+)$#'
  • -l选项会去掉输入的结尾换行符,并在print语句末尾添加一个换行符。
  • -n选项会在脚本周围添加一个while(<>)循环。
  • (?<=//)回顾断言可以找到双斜杠。
  • ...后面跟着非斜杠字符,直到行末。
  • for循环确保不打印不匹配的内容。

-n选项的好处是这个单行命令可以用于管道或文件中。

command | perl -lnwe '...'
perl -lnwe '...' filename

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接