我有以下代码,里面使用'paste'和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)
这样做的正确方法是什么?
答案 0 :(得分: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;
}
答案 1 :(得分:3)
为解决这个错误,Perl的反引号显式使用/ bin / sh来运行命令。你的/ bin / sh不像bash,不懂“&lt;(进程替换)”语法。
我完全同意从Perl调用awk只是愚蠢。
答案 2 :(得分:1)
可以简化以下命令吗?
my $inputString = "paste <\(grep \"target:\" $gTestFile | awk '{print \$4,\$5,\$6,\$7,\$8,\$10,\$11,\$12,\$15,\$16,\$17}'\) $preFile";
my @combinedOutput = `$inputString`;