2012-01-26 33 views
2

目前我使用s3cmd ls s3://location/ > file.txt来获取我的s3存储桶的内容列表并保存在txt文件中。但是,以上返回日期,文件化路径和文件名。s3cmd内容列表 - 只有文件名 - perl一个班轮?

例如:

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

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

这可以用Perl一个班轮完成,也许在初始导出后?

+0

在你不知道的情况下,有CPAN模块,以方便的编程访问S3,例如网::亚马逊:: S3。所以不要打电话给s3cmd,你可以调出相关的方法。 – zgpmax

回答

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 

由于oneliner:

perl -mURI -lne 'print ((URI->new((split q(), $line)[-1])->path_segments)[-1])' < input 
0

我相信一个特定的模块是更安全的选择,但如果数据是可靠的,你可以逃脱一个oneliner:

假设输入为:

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#(?<=//)([^/]+)$#' 
  • -lchomp S上的输入,并增加了新行结束的print声明
  • -n增加了周围的脚本while(<>)循环
  • (?<=//)向后断言找到一个双斜杠
  • ...其后以非斜杠结束行
  • for循环向我们保证不打印不匹配。

-n选项的好处是这个单线程可用于管道或文件中。

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

用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