Awk Conditional Test Statement
I would really appreciate some help. I spent almost the whole morning on it.
I have a data of structure field 1 to 16 as follows
4572 1307084940 RDCSWE 2006 1 5 0.28125 0.5 0.125 0.09375 0 0 0 0 0 0
4573 1307101627 RDCSWE 2006 1 5 0.6875 0.125 0.1875 0 0 0 0 0 0 0
4574 1307101642 RDCSWE 2006 1 5 0.5625 0.25 0.03125 0.15625 0 0 0 0 0 0
4575 1307101662 RDCSWE 2006 1 5 0.53125 0.25 0.1875 0.03125 0 0 0 0 0 0
4576 1307127329 RDCSWE 2006 1 5 0.4375 0.34375 0.09375 0.125 0 0 0 0 0 0
From field 7 to 10 I need a test on the elements (ranging fro 0-1) and the field number.
i.e. for every record, check the fields 7-10 for maximum value,if found and its in field 7 print $0, $6-4
if found and its in field 8 print $0, $6-3 if found and its in field 9 print $0, $6-2 if found and its in field 10 print $0, $6-1I'll be so grateful for the help. Thank you in advance
Edit (by belisarius)
Just transcripting a comment from @Tumi2002 (author)
Sorry, my 6th field (i.e. $6) has values 1-5.
I am trying t开发者_C百科o reclassify records where field 6=5 back into 1-4 classes in the same fieid). So that instead of 5 classes I have 4.Awk '$6==5
{for i=7; i<11; i++)
if ($i==max) && NF==7) print $0,$6-4;
if ($i==max) && NF==8) print $0,$6-3;
if ($i==max) && NF==9) print $0,$6-2;
if ($i==max) && NF==10) print $0,$6-1
I am struggling with the syntax in awk
{
max=0; maxindex=0;
for (i=7; i<=10; i++)
{
if ($i>max){
maxindex=i;
max=$i;
# print i;
}
}
if (maxindex > 0){
print $6-11+maxindex;
}
}
Running at ideone
Output for your example data:
2
1
1
1
1
Edit
Modified answering your comment:
($6 == 5){
max=0; maxindex=0;
for (i=7; i<=10; i++)
{
if ($i>max){
maxindex=i;
max=$i;
# print i;
}
}
if (maxindex > 0){
print $0,"-->",$6-11+maxindex;
}
}
Output:
4572 1307084940 RDCSWE 2006 1 5 0.28125 0.5 0.125 0.09375 0 0 0 0 0 0 --> 2
4573 1307101627 RDCSWE 2006 1 5 0.6875 0.125 0.1875 0 0 0 0 0 0 0 --> 1
4574 1307101642 RDCSWE 2006 1 5 0.5625 0.25 0.03125 0.15625 0 0 0 0 0 0 --> 1
4575 1307101662 RDCSWE 2006 1 5 0.53125 0.25 0.1875 0.03125 0 0 0 0 0 0 --> 1
4576 1307127329 RDCSWE 2006 1 5 0.4375 0.34375 0.09375 0.125 0 0 0 0 0 0 --> 1
Running at ideone here
First of all, thanks for belisarius for pointing to ideone.
My (updated) solution is working correctly now:
# max value in an array, copied verbatim from the gawk manual (credit)
function maxelt(vec, i, ret)
{
for (i in vec) {
if (ret == "" || vec[i] > ret)
ret = vec[i]
}
return ret
}
# Load all fields of each record into nums.
{
delete nums
for(i = 7; i <= 10; i++)
{ nums[NR, i] = $i }
### DEBUG print NR, maxelt(nums)
if ( $7 == maxelt(nums) ) { print $0, ($6-4) }
if ( $8 == maxelt(nums) ) { print $0, ($6-3) }
if ( $9 == maxelt(nums) ) { print $0, ($6-2) }
if ( $10 == maxelt(nums) ) { print $0, ($6-1) }
}
HTH
精彩评论