按年月汇总文件大小,并包括打印时的按年总计

时间:2019-03-22 10:11:28

标签: perl

我在这篇文章中关注@zdim的递归解决方案 fastest way to sum the file sizes by owner in a directory以按年月汇总我的文件大小

perl -MFile::Find -E' use POSIX;
    $dir = shift // "."; 
    find( sub { 
        return if /^\.\.?$/; 
        my ($mtime, $size) = (stat)[9,7];
        my $yearmon = strftime "%Y%m",localtime($mtime);
        $rept{$yearmon} += $size ;
    }, $dir ); 
    say ("$_ => $rept{$_} bytes") for sort keys %rept
'

它给出这样的结果。

201701 => 7759 bytes
201702 => 530246 bytes
201703 => 3573094 bytes
201704 => 425827 bytes
201705 => 3637771 bytes
201706 => 2325391018 bytes
201707 => 127005 bytes
201708 => 2303 bytes
201709 => 231465431 bytes
201710 => 273667 bytes
201711 => 6397659 bytes
201712 => 333587 bytes
201802 => 874676 bytes
201803 => 147825681 bytes
201804 => 84971454 bytes
201805 => 3483547 bytes
201806 => 8004797 bytes
201807 => 184676 bytes
201808 => 1967947 bytes
201809 => 1592310 bytes
201810 => 24176 bytes
201811 => 883378 bytes
201812 => 6661592 bytes
201901 => 33979401 bytes

但是在打印给定年份中所有可用的月份后,我需要按年总计,如下所示

201710 => 1111 bytes
201711 => 2222 bytes
201712 => 3333 bytes
2017  => 6666 bytes ( summed up )
201803 => 11111 bytes
201809 => 22222 bytes
2018  => 33333 bytes ( summed up )

我怎么得到的?一年中的月份中可能会有空白,而不必每年都以第12个月结束。

2 个答案:

答案 0 :(得分:3)

两个小小的改动就可以解决问题。

perl -MFile::Find -E' use POSIX;
    $dir = shift // "."; 
    find( sub { 
        return if /^\.\.?\z/;                             # Fixed $ -> \z
        my ($mtime, $size) = (stat)[9,7];
        my $yearmon = strftime "%Y%m",localtime($mtime);
        $rept{$yearmon} += $size;
        $rept{substr($yearmon, 0, 4)} += $size;           # <---
    }, $dir ); 
    say "$_ => $rept{$_} bytes"
        for sort { "${a}99" cmp "${b}99" } keys %rept;    # <---
'

答案 1 :(得分:2)

鉴于您已经在代码的第一部分中构建了%rept哈希,显示部分应该是这样的:

# Keep track of current year and current year total
my ($year, $year_total);

for (sort keys %rept) {
  # Get the year from the current record
  my $this_year = substr($_, 0, 4);
  # If the year has changed, then print a total line
  # and reset the year total.
  if (defined $year and $year ne $this_year) {
    say "$year   => $year_total bytes";
    $year_total = 0;
  }
  # Add to the year total and store the current year
  $year_total += $rept{$_};
  $year = $this_year;

  say "$_ => $rept{$_} bytes";
}

# Final year total line
say "$year   => $year_total bytes";