我想查看名为missing
的文件,然后查看名为flags
的目录。
missing
中列出的每个文件都将始终显示在flags
目录中。
我想查看flags
目录中的每个文件,然后查看它们是否在missing
文件中。如果其中一个不是,请从flags
目录中删除该文件。
@flags=`ls $dir`;
$flags_size = scalar @flags;
$file = "/home1/t01jkxj/check_st/missing";
$filesize = -s $file;
if ($filesize < $flags_size) {
##What to do??##
}
答案 0 :(得分:1)
您没有描述missing
文件的格式,但我猜它每行包含一个文件,并提供文件的完整绝对路径。如果猜错了,你需要调整这个解决方案。
此程序将missing
文件加载到哈希中。每个哈希元素都有文件名作为键,值为1。
打开flags
目录,并将路径添加到每个文件名以在$filename
中形成绝对路径。如果文件名未出现在%missing
哈希中,则打印文件名。要实际删除文件,应取消注释unlink
行。
use strict;
use warnings;
my $missing = "/home1/t01jkxj/check_st/missing";
open my $fh, '<', $missing or die qq(Unable to open "$missing" for read: $!);
my %missing;
while (<$fh>) {
next unless /\S/;
chomp;
$missing{$_} = 1;
}
my $dir = '/path/to/flags';
opendir my $dh, $dir or die qq(Unable to open directory "$dir": $!);
for my $file (readdir $dh) {
my $filename = "$dir/$file";
unless ($missing{$filename}) {
# unlink $filename;
print qq(File "$filename" deleted as not found in 'missing' file\n);
}
}
答案 1 :(得分:0)
查看哈希值。将所有丢失的条目放入哈希中。然后循环遍历flags目录中的所有文件,并检查它是否在哈希中。如果是,很好,如果没有,删除该文件。
my %missings = map { chomp; $_ => 1 } do {
open my $fh, '<', $missing_file or die "Can't read $missing_file: $!";
<$fh>
};
opendir my $dh, $dir or die "Can't read from $dir: $!";
while(readdir $dh) {
unlink $_ unless delete $missings{$_};
}
# I know, you said this can't happen.
if (keys %missings) {
print "The following are in $missing_file but not in $dir:\n";
print " $_\n" for sort keys %missings;
}
警告:完全未经测试。我在网络浏览器的框中输入了这个。
答案 2 :(得分:0)
现在不在Linux中,但这是你需要做的。此脚本收集文件和数组目录中的文件列表,然后查找两者之间的差异。我会测试,但不能真的) - =。考虑一下伪代码!:
use strict;
use warnings;
my $fi;
my $line;
my @to_delete;
my $var;
my @indir;
my @files;
# the difference of @females and @simpsons
@indir = `ls`;
open($fi, "< list.txt");
while ($line = <$fi>)
{
chomp($line);
push @files, $line;
}
@to_delete=grep(!defined $indir{$_}, @files); #gets difference of the two arrays
print "Delete this:\t$_\n" foreach (@to_delete);
答案 3 :(得分:0)
在我看来,你也可以使用bash命令执行此操作。类似的东西:
cd /path/to/flags; ls | grep -vf missing.txt | xargs rm
注意:请不要在未经测试的情况下运行上述内容。
在perl中,在代码中稍微冗长并发出警告可能是个好主意。当然,可以删除自动作业的警告。
use strict;
use warnings;
my $dir = "/path/to/flags";
chdir $dir or die $!; # change working directory
my @flags = <*>; # get a list of the files
my $file = "/home1/t01jkxj/check_st/missing";
open my $fh, "<", $file or die $!;
chomp(my @missing = <$fh>); # get file names and remove newlines
my %missing = map { $_ => 1 } @missing; # ..and put them in a hash
my @delete;
for my $file (@flags) { # all files not in the hash go into @delete
push @delete, $file unless $missing{$file};
}
if (@delete) { # do not delete without confirmation
print @delete . " files to delete\n@delete\n---\nDelete them all? ";
my $reply = <>;
if ($reply =~ /^y$/) {
unlink $_ or warn "$_: $!" for @delete;
}
} else {
print "No missing files to delete.\n";
}