【问题标题】:Piping output from awk to perl从 awk 到 perl 的管道输出
【发布时间】:2012-09-19 23:08:14
【问题描述】:

我想用从我的 awk 脚本中获得的值在 Perl 中创建一个数组。然后我可以在 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 中的打印语句收集到 perl 中的数组中吗?

我尝试在 perl 中运行 awk 脚本:

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

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

【问题讨论】:

  • 在 Perl 中重新实现逻辑不是更简单吗?它将使用与 awk 代码大致相同数量的代码,并且您无需调用外部进程并在之后解析结果。
  • 所以我仍然需要解析结果,即使我在 awk 中这样做了?有没有办法在 awk [value1, value2...] 中创建一个列表,然后能够在 perl 中使用该列表?

标签: perl parsing unix awk pipe


【解决方案1】:

应该是:

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

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

【讨论】:

  • 是的,我刚刚将 $awk_run 设为 @array 变量,然后得到了我想要的。
【解决方案2】:

从 awk 到你的 perl 脚本:

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

然后从perl里面的stdin读取:

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

【讨论】:

  • 我得到了 sh: fork: 资源暂时不可用
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-02-04
  • 1970-01-01
  • 2020-05-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-27
相关资源
最近更新 更多