管道输出从awk到perl

时间:2012-09-28 04:38:33

标签: perl parsing unix awk pipe

我想在Perl中创建一个数组,其中包含从我的awk脚本中获取的值。然后我可以在Perl中对它们进行数学运算。

这是我的Perl,它运行一个保存文本文件的程序:

my $unix_command_dsc = (`./program -s test.fasta saved_file.txt`);
my $dsc_run = qx($unix_command_dsc);

现在我有一些Awk解析保存在文本文件中的数据:

#!/usr/bin/awk -f

BEGIN{       # Initialize the values to zero. Note, done automatically also.
    sumc4 = 0
    sumc5 = 0
    sumc6 = 0
}

/^[1-9][0-9]* residue/ {next}    #Match line that begins with number and has word 'residue', skip it.
/^[1-9]/ {                       #Match line that begins with number.

    sumc4 += $4                  #Add up the values of the nth column into the variables.
    sumc5 += $5
    sumc6 += $6

    print $4 "\t" $5 "\t" $6    #This will show the whole columns. 

    }

END{
    print "sum H" "\t" "sum E" "\t" "sum C"
    print sumc4 "\t" sumc5 "\t" sumc6  
}

我使用以下命令从终端运行此Awk:

./awk_program.txt saved_file.txt 

我是如何将这些数据从awk中的print语句中收集到perl中的数组中的?

我试过的是在perl中运行awk脚本:

my $unix_command_awk = (`./awk_program.txt saved_file.txt`);
my $awk_run = qx($unix_command_awk);

但perl给了我错误和找不到的命令,就像它认为数据是命令一样。 awk中是否存在我缺少的STDOUT,而不是打印?

2 个答案:

答案 0 :(得分:3)

应该是:

my $awk_run = `./awk_program.txt saved_file.txt`;

反引号告诉perl运行命令并返回输出。因此,您对$ unix_command_awk的分配正在运行该命令,然后qx($unix_command_awk)将输出作为新命令执行。

答案 1 :(得分:1)

从awk管道到你的perl脚本:

./awk_program file.txt | perl perl-script.pl

然后从perl中的stdin读取:

while (<>) {
    # do stuff with $_
    my @cols = split(/\t/);
}