4

我有以下在 Perl 中使用“粘贴”和 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)

正确的方法是什么?

4

3 回答 3

11

不完全确定这是否是对您的脚本的正确解释,因为那里似乎有很多死/未使用的代码,但肯定不需要生成 paste 或 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;
}
于 2009-04-16T03:10:54.037 回答
3

为了解决这个错误,Perl 的反引号明确地使用 /bin/sh 来运行命令。您的 /bin/sh 不像 bash 并且不理解“<(进程替换)”语法。

我完全同意从 Perl 调用 awk 是愚蠢的。

于 2009-04-16T10:29:56.253 回答
1

可以简化以下命令吗?

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

my @combinedOutput = `$inputString`;
于 2012-02-25T16:47:22.423 回答