AWK阵列输出线数以及平均 [英] awk array to output the line count as well as average

查看:115
本文介绍了AWK阵列输出线数以及平均的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于@karakfa以下 AWK 在输出数组结果。我试图 $ 2 添加到阵列中,并输出为好。 $ 2 基本上是时代出现的唯一项目的数量。由于我leaaring AWK 数组我不知道,如果我试图接近。

输入:

  CHR1:955542-955763 AGRN:exon.1 ​​1 0
CHR1:955542-955763 AGRN:exon.1 ​​2 0
CHR1:985542-985763 AGRN:exon.2 1 0
CHR1:985542-985763 AGRN:exon.2 2 1

我的脚本:

 的awk'{K = $ 1 $ OFS 2;
    L = $ 2; # 它是否正确?
    S [K] + = $ 4; C [K] ++}
  END {#为(以秒我)这是正确的?
    打印I,S [I] / C [I]},
      (lbases)#这是正确的?输入

电流输出:

  CHR1:955542-955763 AGRN:exon.1 ​​0
CHR1:985542-985763 AGRN:exon.2 0.5

所需的输出:

  CHR1:955542-955763 AGRN:exon.1 ​​0(2个碱基)
CHR1:985542-985763 AGRN:exon.2 0.5(2个碱基)


解决方案

您尝试引入新的变量是行不通的。你需要每个数组键计数,所以变量应该是另一个数组。但在这种情况下,你并不需要添加一个新的数组,因为数组 C 已经包含了每个键的次数。

 的awk'{K = $ 1 $ OFS 2;
    S [K] + = $ 4; C [K] ++}
  END {了(我在S)
    打印I,S [I] / C [I],C [I]基地}'输入

还要注意你怎么不高兴尝试过基地的结束的结束括号外块。

这不同于问题的描述中,关键是不是 $ 2 ,但 $ 1 的组合和 $ 2 。如果你真正需要的关键是单纯 $ 2 ,你需要一个新的数组,但整个事情将变得相当复杂一点。

Thanks to @karakfa the below awk array results in the output. I am trying to add $2 to the array and output that as well. $2 is basically the amount of times the unique entry appears. As I am leaaring awk arrays I do not know if my attempt is close.

Input:

chr1:955542-955763  AGRN:exon.1 1   0
chr1:955542-955763  AGRN:exon.1 2   0
chr1:985542-985763  AGRN:exon.2 1   0
chr1:985542-985763  AGRN:exon.2 2   1

My script:

awk '{k=$1 OFS $2;
    l=$2;  # Is this correct?
    s[k]+=$4; c[k]++}
  END{for(i in s)  # Is this correct?
    print i, s[i]/c[i]},
      "(lbases)"  # Is this correct?' input

Current output:

chr1:955542-955763 AGRN:exon.1 0
chr1:985542-985763 AGRN:exon.2 0.5

Desired output:

chr1:955542-955763 AGRN:exon.1 0   (2 bases)
chr1:985542-985763 AGRN:exon.2 0.5 (2 bases)

解决方案

Your attempt to introduce a new variable is not going to work. You need a count per array key, so the variable should be another array. But in this case, you don't need to add a new array, because the array c already contains the count per key.

awk '{k=$1 OFS $2;
    s[k]+=$4; c[k]++}
  END{for(i in s)
    print i, s[i]/c[i], c[i] " bases" }' input

Notice also how your attempt unhappily had the "bases" outside the closing brace of the END block.

This differs from the problem description in that the key is not $2, but the combination of $1 and $2. If you genuinely need the key to be solely $2, you do need a new array, but then the whole thing will get quite a bit more complex.

这篇关于AWK阵列输出线数以及平均的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆