2014-09-18 3 views
0

파일 배열이 있습니다. 텍스트 몇 줄의 각 파일은, 그 중 펄에서perl : 파일을 읽는 중 Regex

use strict; 
use warnings; 

foreach my $myfile (@myFiles) { 
    open my $FILE, '<', $myfile or die $!; 
    while (my $line = <$FILE>) { 
     my ($project, $value1, $value2) = <Reg exp>, $line; 
     print "Project : $1 \n"; 
     print "Value1 : $2 \n"; 
     print "Value2 : $3 \n"; 
    } 
    close(FILE); 
} 

* 파일 내용을 정규식을 통해 몇 가지 특정 문자열을 얻기 위해 노력하고 있어요 *

Checking Project foobar 
<few more lines of text here> 
Good Files excluding rules:  15 - 5% 
Bad Files excluding rules: 270 - 95% 

<one more line of text here> 
Good Files including rules:  15 - 5% 
Bad Files including rules: 272 - 95% 
<few more lines of text here> 

* 원하는 출력 *

Project:foobar 
Value1 : Good Files excluding rules:  15 - 5% 
      Bad Files excluding rules: 270 - 95% 
Value2 : Good Files including rules:  15 - 5% 
      Bad Files including rules: 272 - 95% 
+0

'내 $ 파일 '<', $ myfile을이 $ 죽을;'$의 myfile'와'die''사이'or' 누락을 엽니 다!. –

+0

@JimDavis 감사합니다. 업데이트 됨 – Jill448

+0

이 줄은 '좋음/나쁨 제외', '좋음/나쁨 포함'또는 순서가 맞지 않고 인터레이스 된 것처럼 엄격한 순서로 표시됩니까? 또한 Perl을 많이 사용하지 못했습니다.이 ', $ line'이 새로운 구조입니까? – sln

답변

1

하나의 정규식을 만들어 원하는 값을 모두 포착하려고 시도하지 않는 것이 좋습니다.

대신 줄 단위로 처리하고 일치시키려는 각 줄 유형에 대해 정규식을 만듭니다.

use strict; 
use warnings; 

my $fh = \*DATA; 

my $counter = 0; 

while (<$fh>) { 
    if (/Checking Project (\w+)/) { 
     printf "Project:%s\n", $1; 

    } elsif (/^Good Files/) { 
     printf "Value%-2s: %s", ++$counter, $_; 

    } elsif (/^Bad Files/) { 
     printf "  : %s", $_; 
    } 
} 

__DATA__ 
Checking Project foobar 
<few more lines of text here> 
Good Files excluding rules:  15 - 5% 
Bad Files excluding rules: 270 - 95% 

<one more line of text here> 
Good Files including rules:  15 - 5% 
Bad Files including rules: 272 - 95% 
<few more lines of text here> 

출력 :

Project:foobar 
Value1 : Good Files excluding rules:  15 - 5% 
     : Bad Files excluding rules: 270 - 95% 
Value2 : Good Files including rules:  15 - 5% 
     : Bad Files including rules: 272 - 95% 
1

이 같은 정규식을 사용할 수 있습니다

enter image description here

경기 정보

MATCH 1 
1. [54-95] `Good Files excluding rules:  15 - 5%` 
MATCH 2 
1. [96-136] `Bad Files excluding rules: 270 - 95%` 
MATCH 3 
1. [167-208] `Good Files including rules:  15 - 5%` 
MATCH 4 
1. [209-249] `Bad Files including rules: 272 - 95%` 

정규식 이상 사용 Working demo

(good.*|bad.*) 

0, 당신은 당신이 필요로하는 라인을 캡처 할 수 있습니다. 그런 다음 원하는 출력을 생성하기 위해 일부 논리를 추가해야합니다.