我需要创建一个Perl脚本来检查路径中提到的所有文件的文件名的前四个字符,并将其与包含这四个字符的文本文件进行比较。
我们的想法是检查是否缺少任何以数字列表开头的文件。
例如。路径D:/temp
中的文件是
1234-2041-123.txt
1194-2041-123.txt
3234-2041-123.txt
1574-2041-123.txt
我需要将文件名的前四个字母 - 1234
,1194
,3234
,1574
与包含序列1234
的文本文件进行比较,1194
,3234
,1574
,1111
,2222
并发送输出
File starting with 1111, 2222 is missing.
我希望我很清楚。
我可以从文件名中取出前四个字符,但无法继续进行
@files = <d:/temp/*>;
foreach $file (@files) {
my $xyz = substr $file, 8, 4;
print $xyz . "\n";
}
答案 0 :(得分:0)
my @files = <d:/temp/*>;
my %hash;
map { $hash{$_}=0;} qw|1234 1194 3234 1574 1111 2222|;
foreach $file (@files) {
$hash{$1}++ if $file =~ m|mp/(.{4})|;
};
map {
printf "%s -> %d\n",$_,$hash{$_};
} grep {
! $hash{$_}
} keys %hash;
并且,从那里,如果你用以下代码替换3个最后一行(从grep
到结尾):
} sort {
$hash{$a}<=>$hash{$b}
} keys %hash;
您将获得所有匹配文件名的计数
简洁(并且完全符合要求; - )
my @attended = qw|1234 1194 3234 1574 1111 2222|;
my %hash;
map { $hash{$_}=0;} @attended;
map { $hash{$1}++ if m|mp/(.{4})| } <d:/temp/*>;
printf "File starting with %s is missing.. Hope i am clear!\n",
join ", ",map { sprintf "'%s'",$_ } grep { ! $hash{$_} } keys %hash;
答案 1 :(得分:0)
此解决方案通过从文件prefixes.txt
中的所有值创建哈希,然后从每个序列开始找到文件时删除该哈希中的元素。
此外,如果任何文件名以文件中未显示的序列开头,则会打印警告。
输出只是列出在此过程之后剩余的散列的所有元素。
use strict;
use warnings;
my %prefixes;
open my $fh, '<', 'prefixes.txt' or die $!;
while (<$fh>) {
chomp;
$prefixes{$_} = 1;
}
my @files = qw/
1234-2041-123.txt
1194-2041-123.txt
3234-2041-123.txt
1574-2041-123.txt
/;
for my $name (@files) {
my $pref = substr $name, 0, 4;
if ($prefixes{$pref}) {
delete $prefixes{$pref};
}
else {
warn qq{Prefix for file "$name" not listed};
}
}
printf "File starting with %s is missing.\n", join ', ', sort keys %prefixes;
<强>输出强>
File starting with 1111, 2222 is missing.
答案 2 :(得分:0)
与@F相似。 Hauri提出的解决方案,我提出了一个基于哈希的解决方案:
# Get this list from the file. Here, 'auto' and 'cron' will exist in
# /etc, but 'fake' and 'mdup' probably won't.
my @expected_prefixes = qw| auto cron fake mdup |;
# Initialize entries for each prefix in the seed file to false
my %prefix_list;
undef @prefix_list{ @expected_prefixes };
opendir my ${dir}, "/etc";
while (my $file_name = readdir $dir ) {
my $first_four = substr $file_name, 0, 4;
# Increment element for the prefix for found files
$prefix_list{$first_four}++;
}
# Get list of prefixes with no matching files found in the directory
my @missing_files = grep { ! $prefix_list{$_} } keys %prefix_list;
say "Missing files: " . Dumper(\@missing_files);