【问题标题】:join files depending on filenames [closed]根据文件名加入文件[关闭]
【发布时间】:2023-03-14 13:35:01
【问题描述】:

示例文件名:

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 可供我使用。

谢谢

【问题讨论】:

  • 当你说“加入文件”时,我假设你的意思是用 cat file1 file2 ... > allfiles 相同的方式连接文件?

标签: perl list filenames


【解决方案1】:

这是任务的一部分(在 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 文件很有帮助。

【讨论】:

    猜你喜欢
    • 2019-12-24
    • 2014-08-10
    • 2013-03-03
    • 2019-10-05
    • 1970-01-01
    • 2019-11-29
    • 1970-01-01
    • 2015-01-29
    • 1970-01-01
    相关资源
    最近更新 更多