0

我正在编写代码来查找不包含字符串模式的文件。如果我有一个文件列表,我必须查看每个文件的内容,如果文件中没有出现字符串模式“clean”,我想获取文件名。请帮忙。

这是场景:我有一个文件列表,每个文件里面都有很多行。如果文件是干净的,它将有“干净”的措辞。但是如果文件是脏的,“干净”的措辞就不存在,也没有明确的指示来告诉文件是脏的。所以只要在每个文件中,如果没有检测到“干净”的措辞,我会将其归类为脏文件,我想跟踪文件名

4

4 回答 4

4

您可以使用简单的单线:

perl -0777 -nlwE 'say $ARGV if !/clean/i' *.txt

用 slurping 文件-0777,对整个文件进行正则表达式检查。如果没有找到匹配,我们打印文件名。

对于不支持的低于 5.10 的 perl 版本,-E您可以-E-esay $ARGV替换print "$ARGV"

perl -0777 -nlwe 'print "$ARGV\n" if !/clean/i' *.txt
于 2013-01-30T05:23:18.407 回答
2

如果您需要在 Perl 中生成列表,该File::Finder模块将使生活变得轻松。

未经测试,但应该可以工作:

use File::Finder;

my @wanted = File::Finder              # finds all         ..
              ->type( 'f' )            # .. files          ..
              ->name( '*.txt' )        # .. ending in .txt ..
              ->in( '.' )              # .. in current dir ..
              ->not                    # .. that do not    ..
              ->contains( qr/clean/ ); # .. contain "clean"

print $_, "\n" for @wanted;

整洁的东西!

编辑:

现在我对问题有了更清晰的了解,我认为这里不需要任何模块:

use strict;
use warnings;

my @files = glob '*.txt';  # Dirty & clean laundry

my @dirty;

foreach my $file ( @files ) {     # For each file ...

    local $/ = undef;             # Slurps the file in
    open my $fh, $file or die $!;

    unless ( <$fh> =~ /clean/ ) { # if the file isn't clean ..
        push @dirty, $file;       # .. it's dirty
    }

    close $fh;
}

print $_, "\n" for @dirty;        # Dirty laundry list

一旦你掌握了机制,这可以简化为 lagrep等。

于 2013-01-30T05:59:16.850 回答
0
#!/usr/bin/perl


use strict;
use warnings;

open(FILE,"<file_list_file>");
while(<FILE>)
{
my $flag=0;
my $filename=$_;
open(TMPFILE,"$_");
        while(<TMPFILE>)
        {
         $flag=1 if(/<your_string>/);
        }
    close(TMPFILE);
    if(!$flag)
        {
        print $filename;
        }
}
close(FILE);
于 2013-01-30T06:12:37.410 回答
0

像这样的一种方式:

ls *.txt | grep -v "$(grep -l clean *.txt)"
于 2013-01-30T06:17:24.627 回答