2017-06-15 143 views
3

在下面的awk中,我将$7分割为:,然后计算每行或NM_xxxx。如果$1的值对于每行都是相同的,则打印$7,该值最匹配$1值。 awk似乎接近,但我不知道发生了什么。我包括一个描述以及我认为正在发生的事情。谢谢 :)。awk在匹配字段中打印大多数匹配项

AWK

awk -F'[\t:]' '{count[$7]++} END {for (word in count) print $1, word, count[word]}' file 

描述

awk -F'[\t:]' ---- regex for FS `\t` and split `:` 
'{count[$7]++} ---- count each `line in $7` and read into array count 
{for (word in count) ---- start loop using array count and read each line in array word 
print $1, word, count[word]} ---- print desired fields `$1, [word] (only print count[word] to confirm, it is not needed) 

文件

A2Mcoding na NM_000014.5:c.2998A>G c.2998A>G 
A2M 2 18172 33211 coding na NM_000014.5:c.2915G>A c.2915G>A 
A2M 2 18173 33212 coding na NM_000014.4:c.2125+1_2126-1del c.2125+1_2126-1del 
A2M 2 18174 33213 coding na NM_000014.5:c.2111G>A c.2111G>A 
A2M 2 402328 390084 coding na NM_000014.5:c.2126-6_2126-2delCCATA 
A4GALT 53947 2692 17731 coding na NM_017436.5:c.548T>A c.548T>A 
A4GALT 53947 2693 17732 coding na NM_017436.5:c.752C>T c.752C>T 
A4GALT 53947 2694 17733 coding na NM_017436.6:c.783G>A c.783G>A 
A4GALT 53947 2695 17734 coding na NM_017436.6:c.560G>A c.560G>A 
A4GALT 53947 2696 17735 coding na NM_017436.6:c.240_242delCTT 
A4GALT 53947 2697 17736 coding na NM_017436.6:c.1029dupC c.1029dupC 
A4GALT 53947 39437 48036 coding na NM_017436.6:c.631C>G c.631C>G  

电流输出

2 
NM_017436.6 5 
NM_000014.4 1 
NM_000014.5 4 
NM_017436.5 2 

期望的输出

A2M NM_000014.5 
A4GALT NM_017436.6 

回答

2

随着GNU AWK真正的多维数组:

$ cat tst.awk 
BEGIN { FS="[\t:]" } 
{ 
    cnt[$1][$7]++ 
    max[$1] = (max[$1] > cnt[$1][$7] ? max[$1] : cnt[$1][$7]) 
} 
END { 
    for (word in cnt) { 
     for (val in cnt[word]) { 
      if (cnt[word][val] == max[word]) { 
       print word, val 
      } 
     } 
    } 
} 

$ awk -f tst.awk file 
A4GALT NM_017436.6 
A2M NM_000014.5 
+1

非常感谢你:)。 – Chris

1

在我们不能制表符和空格之间区分的问题的文件。 只需在密钥中添加$1即可。

awk -F'[\t:]' '{count[$1 "\t" $7]++} END {for (word in count) print word, count[word]}' file 
+1

那就是','是 - '算[$ 1,$ 7] ++' –