2017-04-03 22 views
0

我有一个看起来像这样的文件:打印多线,相同的“最大”值用awk

3, abc, x 
2, def, y 
3, ghi, z 

我想找到$1的最高值,并打印包含在这个最高值的所有行$1

sort -t, -k1,1n| tail -n1 

将只提供包含在$1 3行之一,但我两者都需要。

任何建议都赞赏(:

回答

2

我不知道这是否是获得线,而他们与awk的相同值的最好方式,但:

awk 'NR == 1 { t = $1; print } NR > 1 { if (t != $1) { exit; } print }' 

可结合与sort如下:

sort -t, -k1,1nr | awk 'NR == 1 { t = $1; print } NR > 1 { if (t != $1) { exit; } print }' 

还有这个,但它确实不必要的工作:

sort -t, -k1,1nr | awk 'NR == 1 { t = $1 } t == $1 { print }' 
0

这是另一种不需要排序的方法,但需要两遍数据。

max=$(awk -F',' '{if(max < $1) max = $1}END{print max}' Input.txt) 
awk -v max=$max -F',' '$1 == max' Input.txt 
0

在AWK中,只有一个传过来的数据:

$ awk -F, ' 
$1>m {     # when new max is found 
    delete a; m=$1; i=0 # reset all 
} 
a[1]=="" || $1==m {  # if $1 equals max or we're processing the first record 
    a[++i]=$0   # store the record to a 
}   
END {     # in the end 
    for(j=1;j<=i;j++) 
     print a[j]  # print a with stored records 
}  
' file 
3, abc, x 
3, ghi, z