如何在 Perl 中检查非空文件

发布于 12-23 03:08 字数 184 浏览 3 评论 0原文

我使用 find 命令在目录中查找文件。我想在继续之前检查目录中的文件是否不为空(非 0 大小)。感谢 find 手册,我知道如何使用 -empty 选项识别空文件。

但是,我想使用 Perl 来检查非空文件。我怎样才能做到这一点?

提前致谢。

I'm using the find command for finding files in directories. I would like to check if the files in the directories are not empty (non 0 size) before proceeding. Thanks to the find manual, I know how to identify empty files using the -empty option.

However, I want to use Perl to check for non-empty files. How can I do that?

Thanks in advance.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

栖竹2024-12-30 03:08:54

请参阅 perldoc perlfunc -X 了解Perl 文件测试运算符。您想要的是这个:

-s  File has nonzero size (returns size in bytes).

显示如何使用 File::Find 的简单脚本:

#!/usr/bin/perl -w
use strict;

use File::Find;

# $ARGV[0] is the first command line argument
my $startingDir = $ARGV[0];

finddepth(\&wanted, $startingDir);

sub wanted
{
    # if current path is a file and non-empty
    if (-f $_ && -s $_)
    {
        # print full path to the console
        print $File::Find::name . "\n";
    }
}

在此示例中,我将输出发送到控制台。要将其通过管道传输到文件,您只需使用 shell 输出重定向,例如 ./findscript.pl /some/dir > somefile.out

Refer to perldoc perlfunc -X for a refresher of the Perl file test operators. What you want is this one:

-s  File has nonzero size (returns size in bytes).

Simple script showing how to use File::Find:

#!/usr/bin/perl -w
use strict;

use File::Find;

# $ARGV[0] is the first command line argument
my $startingDir = $ARGV[0];

finddepth(\&wanted, $startingDir);

sub wanted
{
    # if current path is a file and non-empty
    if (-f $_ && -s $_)
    {
        # print full path to the console
        print $File::Find::name . "\n";
    }
}

In this example I have the output going to the console. To pipe it to a file, you can just use shell output redirection, e.g. ./findscript.pl /some/dir > somefile.out.

南风几经秋2024-12-30 03:08:54

请查看 perldoc http://perldoc.perl.org/functions/-X。 html

-z  File has zero size (is empty).
-s  File has nonzero size (returns size in bytes).

检测非空文件的示例用法:

unless ( (-z $FILE) ) { process_file($FILE); }
if (-s $FILE) { process_file($FILE); }

Please have a look at perldoc http://perldoc.perl.org/functions/-X.html

-z  File has zero size (is empty).
-s  File has nonzero size (returns size in bytes).

Sample usage to detect non-empty file:

unless ( (-z $FILE) ) { process_file($FILE); }
if (-s $FILE) { process_file($FILE); }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文