如何在perl文件夹的所有文件中查找第一次出现的字符串

时间:2013-02-07 22:34:05

标签: perl

我正在尝试在文件夹中的每个txt文件中找到第一次出现字符串“victory”的行。对于文件中的每个第一个“胜利”,我想将该行中的数字保存到@num,将文件名保存到@filename

示例:对于以行开头的文件a.txt:“lalala victory 123456” - > $ num [$ i] = 123456和$ filename [$ i] =“a.txt”

ARGV拥有所有文件名。我的问题是,我正在尝试逐行,我不知道我做错了什么。 还有一件事 - 我怎样才能在最后一个文件中获得最后一次“胜利”?

use strict;
use warnings;
use File::Find;

my $dir = "D:/New folder";   
find(sub { if (-f && /\.txt$/) { push @ARGV, $File::Find::name } }, $dir);   $^I = ".bak"; 

my $argvv;
my $counter=0;
my $prev_arg=0;
my $line = 0;

my @filename=0;
my @num=0;
my $i = 0;

foreach $argvv (@ARGV)
{
    #open $line, $argvv or die "Could not open file: $!";
    my $line = IN 
    while (<$line>)
    {
        if (/victory/)
        {
            $line = s/[^0-9]//g;    
            $first_bit[$i] = $line;
            $filename[$i]=$argvv;
            $i++;
            last;
        }

    }
    close $line;
}


for ($i=0; $i<3; $i++)
{
    print $filename[$i]."  ".$num[$i]."\n";
}

非常感谢! :)

2 个答案:

答案 0 :(得分:1)

您的示例脚本存在许多小问题。以下示例应该以相当干净的方式执行您想要的操作:

#!/usr/bin/perl 
use strict;
use warnings;
use File::Find;

# Find the files we're interested in parsing
my @files = ();
my $dir = "D:/New folder";
find(sub { if (-f && /\.txt$/) { push @files, $File::Find::name } }, $dir);

# We'll store our results in a hash, rather than in 2 arrays as you did
my %foundItems = ();

foreach my $file (@files)
{
    # Using a lexical file handle is the recommended way to open files
    open my $in, '<', $file or die "Could not open $file: $!";
    while (<$in>)
    {
        # Uncomment the next two lines to see what's being parsed
        # chomp; # Not required, but helpful for the debug print below
        # print "$_\n"; # Print out the line being parsed; for debugging

        # Capture the number if we find the word 'victory'
        # This assumes the number is immediately after the word; if that
        # is not the case, it's up to you to modify the logic here
        if (m/victory\s+(\d+)/)
        {
            $foundItems{$file} = $1; # Store the item
            last;
        }
    }
    close $in;
}

foreach my $file (sort keys %foundItems)
{
    print "$file=> $foundItems{$file}\n";
}

答案 1 :(得分:0)

下面在所有文件(文件* .txt)中搜索字符串abc,并仅打印第一行。

perl -lne 'BEGIN{$flag=1}if(/abc/ && $flag){print $_;$flag=0}if(eof){$flag=1}' file*.txt

测试:

> cat temp
abc 11
22
13
,,
abc 22
bb
cc
,,
ww
kk
ll
,,

> cat temp2
abc t goes into 1000
fileA1, act that abc specific place

> perl -lne 'BEGIN{$flag=1}if(/abc/ && $flag){print $_;$flag=0}if(eof){$flag=1}' temp temp2
abc 11
abc t goes into 1000
>