【问题标题】:Using Perl to find a keyword from a file and output to a text file使用 Perl 从文件中查找关键字并输出到文本文件
【发布时间】:2014-02-16 15:22:25
【问题描述】:

我有一个包含路径列表的文本文件。
例如 path.txt

/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);  
}  

【问题讨论】:

  • perl 中的 grep 与 shell 命令 grep(1) 完全不同。它需要在第二个参数中使用 LIST。请参阅 perldoc,perldoc.perl.org/functions/grep.html
  • 听起来像是一个shell命令任务:cat path.txt | while read -r file; do grep 'Total Output Is' "$file/report.txt"; done &gt; output.txt

标签: perl unix


【解决方案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);

【讨论】:

    【解决方案2】:

    为什么不使用简单明了的老bash

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

    【讨论】:

      猜你喜欢
      • 2021-10-14
      • 1970-01-01
      • 2015-03-18
      • 1970-01-01
      • 1970-01-01
      • 2011-03-16
      • 2022-10-29
      • 1970-01-01
      • 2013-07-19
      相关资源
      最近更新 更多