2009-04-16 101 views
4

我有以下代碼,它使用'粘貼'和AWK腳本 Perl。如何在Perl中使用paste和awk?

use strict;    
use Data::Dumper;   
use Carp; 
use File::Basename;  

my @files = glob("result/*-*.txt"); 
my $tocheck = $ARGV[0] || "M"; 


foreach my $file (@files ) { 
    my $base = basename($file,".txt"); 
    my @res = `paste <\(awk '\$4 == "M" {sum += \$2 }END{print sum}' $file \) <\(awk '\$4 == "M" {sum += \$3 }END{print sum}' $file\)`; 
    chomp(@res);   
    print "$base $res[0]\n";  
} 

爲什麼它給出了這樣的錯誤:

#sh: -c: line 1: syntax error near unexpected token `(' 
#sh: -c: line 1: `paste <(awk '$4 == "M" {sum += $2 }END{print sum}' result/9547_1-S_aureus.txt) <(awk '$4 == "M" {sum += $3 }END{print sum}' 
#result/9547_1-S_aureus.txt) 

什麼是做正確的方法是什麼?

+2

perl 1.0被認爲是AWK的*替換*。牢記未來。 – 2009-04-16 07:52:30

回答

11

不能完全確定,如果這是你的腳本的正確解釋,因爲似乎是一個大量的死/無用的代碼有,但肯定是有沒有必要去產卵粘貼或awk來做到這一點:

#!/usr/bin/perl 
use warnings; 
use strict; 
use File::Basename; 

my @files = glob ("result/*-*.txt"); 

foreach my $file (@files) { 
    open (FILE, $file) or die "open $file: $!\n"; 
    # You seem to be summing the 2nd and 3rd columns if the 4th is "M" 
    my ($col1, $col2) = (0, 0); 
    while (<FILE>) { 
     my @cols = split /\s+/; 
     if ($cols[3] eq "M") { 
      # Perl uses 0-based arrays, unlike awk 
      $col1 += $cols[1]; 
      $col2 += $cols[2]; 
     } 
    } 
    close FILE; 
    printf "%s %d\n", basename ($file), $col1; 
} 
3

爲了解決這個錯誤,Perl的反引用顯式地使用/ bin/sh來運行該命令。您的/ bin/sh不是bash,並且不理解「<(進程替換)」語法。

我完全同意從Perl調用awk是愚蠢的。

1

可以簡化下面的命令嗎?

my $inputString = "paste <\(grep \"target:\" $gTestFile | awk '{print \$4,\$5,\$6,\$7,\$8,\$10,\$11,\$12,\$15,\$16,\$17}'\) $preFile"; 

my @combinedOutput = `$inputString`;