awk将文件1与文件2和平均字段7

时间:2015-11-16 13:50:37

标签: awk

我正在尝试匹配file 1中的所有file 2名称,并在匹配时对其进行平均。匹配的字段在$5符号前面为|,平均值是与$7匹配的$4的总和。谢谢你:)。

档案1

AGRN 
CYP2J2

文件2

chr1    955543  955763  chr1:955543 AGRN-6|gc=75    1   2
chr1    955543  955763  chr1:955543 AGRN-6|gc=75    2   2
chr1    955543  955763  chr1:955543 AGRN-6|gc=75    3   2
chr1    957571  957852  chr1:957571 AGRN-7|gc=61.2  1   148
chr1    957571  957852  chr1:957571 AGRN-7|gc=61.2  2   149
chr1    957571  957852  chr1:957571 AGRN-7|gc=61.2  3   151
chr1    60381600    60381782    chr1:60381600   CYP2J2-1596|gc=40.7 153 274
chr1    60381600    60381782    chr1:60381600   CYP2J2-1596|gc=40.7 154 273

所需的输出(制表符分隔)

chr1:955543     AGRN-6     2
chr1:957571     AGRN       149.3
chr1:60381600   CYP2J2-1596     153.5

到目前为止我已尝试过:

awk '
 FNR==NR{d[$0]; next;}          
 {                              
     for(k in d){               
         pat="(^|;)"k":";       
         if($5 ~ pat){
             print;             
             break;
         }
     }
 }' file 1 file2 > output.bed

awk确实运行,但截至目前,输出文件为0字节。谢谢你:)。

1 个答案:

答案 0 :(得分:2)

脚本应如下所示:

test.awk

BEGIN {
  FS="[ \t|]*"
}
# Read search terms from file1 into 's'
FNR==NR {
    s[$0]
    next
}
{
    # Check if $5 matches one of the search terms
    for(i in s) {
        if($5 ~ i) {

            # Store first two fields for later usage
            a[$5]=$1
            b[$5]=$2

            # Add $9 to total of $9 per $5
            t[$5]+=$8
            # Increment count of occurences of $5
            c[$5]++

            next
        }
    }
}
END {

    # Calculate average and print output for all search terms
    # that has been found
    for( i in t ) {
        avg = t[i] / c[i]
        printf("%s:%s\t%s\t%s\n", a[i], b[i], i, avg)
    }
}

称之为:

awk -f test.awk file1 file2

顺便说一下,你预期输出中的第三个平均值是错误的。输出应如下所示:

chr1:955543 AGRN-6  2
chr1:957571 AGRN-7  149.333
chr1:60381600   CYP2J2-1596 273.5