2016-07-19 7 views
1

파일 이름에 따라 폴더의 여러 텍스트 파일에서 특정 줄을 인쇄하려고합니다. 밑줄로 구분 된 3 단어로 명명 된 다음 텍스트 파일을 고려하십시오.여러 텍스트 파일에서 특정 줄을 추출합니다.

Small_Apple_Red.txt 
Small_Orange_Yellow.txt 
Large_Apple_Green.txt 
Large_Orange_Green.txt 

어떻게 다음과 같이 달성 할 수 있습니까?

if (first word of file name is "Small") { 
    // Print row 3 column 2 of the file (space delimited); 
} 

if (second word of file name is "Orange") { 
    // print row 1 column 4 of the file; 
} 

awk에서도 가능합니까?

답변

0

다음과 같이 시도해보십시오.

glob을 사용하면 폴더의 파일을 처리 할 수 ​​있습니다.

그런 다음 정규식을 사용하여 파일 이름을 확인하십시오. 여기 grep은 파일에서 특정 내용을 추출하는 데 사용됩니다.

my $path = "folderpath"; 
while (my $file = glob("$path/*")) 
{ 
    if($file =~/\/Small_Apple/) 
    { 
     open my $fh, "<", "$file"; 
     print grep{/content what you want/ } <$fh>; 
    } 

} 
+0

Perl 용입니까? – amatek

+0

@amatek 예. 이것은 perl을위한 것이다. – mkHun

0
use strict; 
use warnings; 

my @file_names = ("Small_Apple_Red.txt", 
        "Small_Orange_Yellow.txt", 
        "Large_Apple_Green.txt", 
        "Large_Orange_Green.txt"); 

foreach my $file (@file_names) { 
    if ($file =~ /^Small/){ // "^" marks the begining of the string 
     print "\n $file has the first word small"; 
    } 
    elsif ($file =~ /.*?_Orange/){ // .*? is non-greedy, this means that it matches anything<br> 
            // until the first "_" is found 
     print "\n $file has the second word orange"; 
    } 
} 

는 여전히 파일이 "Small_Orange는"당신이 더 중요 결정해야 할이 특별한 경우가 있습니다. 두 번째 단어가 더 중요한 경우, awk는에서 elsif 섹션

0

에서 컨텐츠와 if 섹션의 내용을 전환 :

awk 'FILENAME ~ /^Large/ {print $1,$4} 
    FILENAME ~ /^Small/ {print $3,$2}' * 

펄 :

perl -naE 'say "$F[0] $F[3]" if $ARGV =~ /^Large/; 
      say "$F[2] $F[1]" if $ARGV =~ /^Small/ ' * 
0

이 하나의 시도 :

use strict; 
use warnings; 
use Cwd; 
use File::Basename; 

my $dir = getcwd(); #or shift the input values from the user 
my @txtfiles = glob("$dir/*.txt"); 

foreach my $each_txt_file (@txtfiles) 
{ 
    open(DATA, $each_txt_file) || die "reason: $!"; 
    my @allLines = <DATA>; 
    (my $removeExt = $each_txt_file)=~s/\.txt$//g; 
    my($word1, $word2, $word3) = split/\_/, basename $removeExt; #Select the file name with matching case 
    if($word1=~m/small/i) #Select your match case 
    { 
     my @split_space = ""; 
     my @allrows = split /\n/, $allLines[1]; #Mentioned the row number 
     my @allcolns = split /\s/, $allrows[0]; 
     print "\n", $allcolns[1]; #Mentioned the column number 
    } 
} 
관련 문제