我需要使用Perl按日期计算文件夹中的文件数。这是我的代码:
pd.DataFrame({'id': sorted(id * len(st)), 'st': st * len(id)})
答案 0 :(得分:3)
与Kjetil S.的解决方案一样,该解决方案接受文件名而不是目录名,以提供比您所请求的解决方案更加灵活的解决方案。
此版本解决了Kjetil S.的许多问题。
用法示例:
\ls | num_files_by_date
\ls /some/dir | num_files_by_date
\ls -d /some/dir/*.txt | num_files_by_date
find dir1 dir2 | num_files_by_date
代码:
#!/usr/bin/perl
use strict;
use warnings;
use File::stat qw( stat );
use POSIX qw( strftime );
my %counts_by_date;
while (<>) {
chomp;
my $stat = stat($_)
or do {
warn("Can't stat \"$_\": $!\n");
next;
};
++$counts_by_date{ strftime("%F", localtime($stat->mtime)) }
if !-d $stat; # Don't count dirs.
}
printf("%s %s\n", $_, $counts_by_date{$_})
for sort keys %counts_by_date;
答案 1 :(得分:2)
#!/usr/bin/perl
use warnings; use strict;
my($n,%n)=(0);
while(<>){
chomp;
next if !-f$_; #just count files, ignore dirs, symlinks etc
my $mtime=(stat($_))[9];
my @lt=localtime($mtime); $lt[5]+=1900; $lt[4]+=1;
my $date=sprintf"%04d-%02d-%02d", @lt[5,4,3];
$n{$date}++;
$n++;
}
my @d=sort keys %n;
printf "Date $_ has %3d files\n",$n{$_} for @d;
print "A total of $n files between $d[0] and $d[-1]\n";
另存为num_files_by_date.pl
和chmod +x num_files_by_date.pl
。该程序将在STDIN上获取文件列表,并在每个日期对数字进行计数。像这样运行示例:
\ls -1 | ./num_files_by_date.pl
\ls -d1 /root/perl/* | perl num_files_by_date.pl
find dir1/ dir2/ | ./num_files_by_date.pl
输出可能是:
Date 2019-04-28 has 2 files
Date 2019-04-30 has 3 files
Date 2019-05-03 has 1 files
Date 2019-05-06 has 4 files
A total of 10 files between 2019-04-28 and 2019-05-06