【问题标题】:How can I use paste and awk inside Perl?如何在 Perl 中使用 paste 和 awk?
【发布时间】:2010-10-19 18:26:21
【问题描述】:

我有以下使用“粘贴”和 AWK 脚本的代码 Perl。

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)

正确的做法是什么?

【问题讨论】:

  • perl 1.0 被认为是 AWK 的替代。请牢记这一点,以备不时之需。

标签: linux perl unix awk paste


【解决方案1】:

不完全确定这是否是对您的脚本的正确解释,因为那里似乎有很多死/未使用的代码,但肯定不需要生成 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;
}

【讨论】:

    【解决方案2】:

    为了解决这个错误,Perl 的反引号明确地使用 /bin/sh 来运行命令。您的 /bin/sh 不像 bash 并且不理解“

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

    【讨论】:

      【解决方案3】:

      下面的命令可以简化吗?

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-12-23
        • 2020-11-19
        • 2012-02-18
        • 1970-01-01
        • 1970-01-01
        • 2017-11-18
        • 2011-07-21
        相关资源
        最近更新 更多