2013-02-07 2 views
0

폴더의 각 txt 파일에서 "victory"문자열의 첫 번째 줄을 찾으려고합니다. 파일의 각 "승리"에 대해 해당 줄의 번호를 @num에 저장하고 파일 이름을 @filename으로 저장하려고합니다.펄의 폴더에있는 모든 파일에서 문자열의 첫 번째 항목을 찾는 방법

예 : "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"; 
} 

대단히 감사합니다. :)

+0

'마지막 occurrence' 및 태그 findfirst'있는':

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

테스트? 정말? – TLP

답변

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"; 
} 
+0

고마워요! 나는 당신의 코드를 사용했고 웬일인지 라인 번호가 짝수 인 라인만을 읽었다 : 두 번째 라인, 네 번째 라인, 여섯 번째 라인 ... 나는 그것이 어떻게 될 수 있는지 정말로 이해하지 못한다. 내가 정말로 멍청한 놈이기 때문에 나는 그것에 대한 약간의 도움에 정말로 감사 할 것이다. 감사! – MiSo

+0

'while' 루프는 처리하는 각 파일의 모든 행을 읽지 만'victory '의 첫 번째 인스턴스 만 저장합니다. 히트 곡이 짝수 라인에있을 수 있습니까? 루프에 print 문 ('print "$ _ \ n";')을 추가하여 구문 분석 대상을 정확하게 볼 수 있습니다. 또한 루프 상단에'chomp; '를 추가하는 것이 도움이 될 수 있습니다. 이 예제를 포함하도록 예제를 수정합니다. –

+0

그것은 작동합니다! 고맙습니다! 내 문제는 내부 루프에서 $ line = <$in>을 썼다는 것이므로 모든 두 번째 줄이 있습니다. 지금 나에게 의미가있다. 그것은 꽤 어리석은 실수였습니다. 도와 주셔서 감사합니다. – MiSo

0

아래의 검색 문자열의 모든 파일에서 ABC (파일 *이 .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 
> 
관련 문제