如何在bash中找到最新的匹配模式文件

时间:2013-05-23 19:13:30

标签: bash

我正在尝试仅复制Bash中最新版本的文件。

例如在我的下面脚本中,我正在复制所有文件,但现在我需要复制最新版本(最新版本将作为文件名中的最后一个参数)。

我的文件名示例:

AAA_BBB_CCC_1
AAA_BBB_CCC_2  # I need to copy this file instead the above one because it has
               # _2 which means it is the latest version.

BBB_CCC_DDD_1
BBB_CCC_DDD_2  # I need to copy this file

1 个答案:

答案 0 :(得分:0)

我很懒,所以我会使用Perl。基于'版本是下划线后跟名称末尾的数字',您可以使用它来读取每行一个文件作为输入,并在输出中生成每个文件的最新版本:

#!/usr/bin/env perl
use strict;
use warnings;

my %files;

while (<>)
{
    chomp;
    my($base, $vrsn) = m/(.*)_(\d+)$/;
    $files{$base} //= $vrsn;    # Set if not yet defined
    $files{$base}   = $vrsn if ($vrsn > $files{$base});
}

foreach my $base (sort keys %files)
{
    print "${base}_$files{$base}\n";
}

您可以根据需要将其放入管道中。

相关问题