2014-02-15 100 views
1

我有一個包含路徑列表的文本文件。
e.g path.txt使用Perl從文件中查找關鍵字並輸出到文本文件

/project/results/ver1/ 
/project/results/ver2/ 
/project/results/ver1000/ 

,並在每個路徑它包含一個名爲report.txt檔。 我正在寫一個perl程序來逐行讀取path.txt文件並下降到路徑中並grep文件report.txt。
我需要通過使用grep函數捕獲文件中的關鍵字。
然後我會將我的結果提取到另一個文本文件。

我試過編寫perl程序,它似乎不起作用。 請原諒我,因爲我還是編程新手。

my $output = ("output.txt"); 
my $path = ("path.txt"); 
open (OUT,'>',$output) or die; 
open (PATH, '<',$path) or die; 
foreach (<PATH>){ 
chomp; 
$path1 = $_; 
chdir ("$path1"); 
my $ans = grep 'Total Output Is' , report.txt; 
print OUT "$ans\n"; 
chdir($pwd); 
} 
+0

'grep'在Perl是從外殼命令完全不同的grep'(1)'。它需要第二個參數中的LIST。請參閱perldoc,http://perldoc.perl.org/functions/grep.html – ernix

+0

,它聽起來像一個shell命令任務:'cat path.txt |同時讀取-r文件; grep'Total Output Is'「$ file/report.txt」; done> output.txt' – ernix

回答

1
my $output = "output.txt"; 
my $path = "path.txt"; 
open (OUT, '>', $output) or die $!; 
open (PATH, '<', $path) or die $!; 

while (my $path1 = <PATH>) { 
    chomp $path1; 

    open my $fh, "<", "$path1/report.txt" or die $!; 
    /Total Output Is/ and print OUT $_ while <$fh>; 
    close($fh); 
} 

close(OUT); 
close(PATH); 
0

爲什麼不使用簡單而直接的普通老式bash

while read path; do 
    grep 'Total Output Is' "$path"/report.txt 
done <path.txt> output.txt 
相關問題