根据文件名连接文件

时间:2013-03-07 13:21:20

标签: perl list filenames

示例文件名:

example_12345_8943759847.csv
example_23456_9859877.csv
example_34567_92837458738.csv
example_12345_1165253.csv
example_23456_9983632652.csv
example_23456_2345.csv

我需要加入具有相同中间数的文件,例如。 23456 的.csv 事情是我不知道这个中间数字所以我想这必须是一些变量? 我想我必须列出具有相同中间部分编号的文件名,然后输出这个列表?

我只有Perl或sed可供我使用。

由于

1 个答案:

答案 0 :(得分:2)

这是任务的一部分(在Perl中)。查找共享中间部分的文件组:

use strict;
use warnings;

my @files = qw/
    example_12345_8943759847.csv
    example_23456_9859877.csv
    example_34567_92837458738.csv
    example_12345_1165253.csv
    example_23456_9983632652.csv
    example_23456_2345.csv
/;

my %middles;

#This creates a hash. The keys are the middle number; 
#the values are arrays of filenames that share that middle number.
foreach (@files)
{
    push @{$middles{$1}},$_ if (/[a-z]+_(\d+)_\d+\.csv/);
}

#Now process the results
foreach my $middle (keys %middles)
{
    #Get a group of filenames sharing the same middle part.
    my @files_to_join = @{$middles{$middle}};

    #Join them here...
}

其余的取决于你所说的“加入”。您可能会发现Text::CSV module对处理CSV文件很有帮助。