我试图检查我的文件夹是否为空(0字节)的文件。我有大约1,200个文件,所以Perl将使这项任务变得非常简单:)如何在当前目录中输出空文件的名称?
这是我的代码,但它似乎并没有工作。 (这只是列出所有的文件。)任何人都可以教我我做错了什么?谢谢!
#!/usr/bin/perl
@files = glob('*');
if ((-s @files) == 0) {
print"@files\n";
}
我试图检查我的文件夹是否为空(0字节)的文件。我有大约1,200个文件,所以Perl将使这项任务变得非常简单:)如何在当前目录中输出空文件的名称?
这是我的代码,但它似乎并没有工作。 (这只是列出所有的文件。)任何人都可以教我我做错了什么?谢谢!
#!/usr/bin/perl
@files = glob('*');
if ((-s @files) == 0) {
print"@files\n";
}
#!/usr/bin/perl
use strict; use warnings;
foreach my $file (glob('*')) {
unless (-s $file) {
print "$file\n";
}
}
你做一个检查,但你有多个文件。显然,这没有意义。你需要添加一个循环来检查每个文件。
#!/usr/bin/perl
use strict;
use warnings;
my @files = grep { -s $_ == 0 } glob('*');
# or: grep { ! -s $_ }
# or: grep { -z $_ }
# or: grep { -z }
# or: grep -z,
print "@files\n";
在你的版本,你正在试图将命名为12
文件或任何的@files
元素的数量是规模。结果,-s
正在返回undef
与$!{ENOENT}
集合。
要在当前目录下搜索所有级别时查看它是如何完成的,请考虑标准工具find2perl
的输出。
$ find2perl . -type f -size 0c
#! /usr/bin/perl -w
eval 'exec /usr/bin/perl -S $0 ${1+"[email protected]"}'
if 0; #$running_under_some_shell
use strict;
use File::Find();
# Set the variable $File::Find::dont_use_nlink if you're using AFS,
# since AFS cheats.
# for the convenience of &wanted calls, including -eval statements:
use vars qw/*name *dir *prune/;
*name = *File::Find::name;
*dir = *File::Find::dir;
*prune = *File::Find::prune;
sub wanted;
# Traverse desired filesystems
File::Find::find({wanted => \&wanted}, '.');
exit;
sub wanted {
my ($dev,$ino,$mode,$nlink,$uid,$gid);
(($dev,$ino,$mode,$nlink,$uid,$gid) = lstat($_)) &&
-f _ &&
(int(-s _) == 0)
&& print("$name\n");
}
运行上面的代码
$ find2perl . -type f -size 0c | perl
适应这方面的知识,以你的情况
my @files = grep -f $_ && -s _ == 0, glob "*";
print @files, "\n";
或在一个单一的呼叫print
与
print +(grep -f $_ && -z _, <*>), "\n";
使用SP特定的_
文件句柄包含最新的stat
结果的缓存副本,避免了在操作系统中有足够的两个陷阱。请注意额外检查该文件是否是纯文件(-f
),因为零大小检查(-s _ == 0
或-z _
)对于某些文件系统上的空目录将返回true。
OP没有递归搜索,所以你需要添加'-maxdepth 1' – ikegami
我推荐一个和所有其他解决方案非常相似的解决方案,但我建议您使用-z运算符而不是-s运算符。
在我的脑海里,它更清晰的代码“如果该文件是零长度”,而不是“除非文件具有非零长度”
都具有相同的布尔意义,但前者码你的意图更清楚。否则,你得到的答案都很好。
#/run/my/perl
use strict;
use warnings;
foreach my $file (glob("*")) {
print "$file\n" if -z $file;
}
但做的事情在Perl
use File::stat;
foreach (glob('*')){
print stat($_)->size,"\n"
};
# this will file sizes of all files and directories
# you need to check if its a file and if size is zero
我跑了这一点,它没有工作,要么/另一种方式:无印,但我知道一个事实,因为我的几个这些文件的存在已经手工找到了它们。 –
啊!我将<箭头括号>更改为(括号),代码正常工作! –
sputnik正在考虑'while(<*>)' – ikegami