我如何在Perl中使用粘贴和awk?

我有以下代码,在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) 

什么是正确的方法来做到这一点?

不完全确定这是否是对你的脚本的正确解释,因为在那里似乎有很多死/未使用的代码,但是肯定没有必要去产卵粘贴或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; } 

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

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

下面的命令可以简化吗?

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