ksennin
September 6, 2017, 10:20am
1
Dear Unix gurus,
I have sample data organised like this and containing 6 columns (with headers):
label c2 c3 c4 c5 c6
where c2 to c6 are numeric values in columns c2 to 6.
I am trying to create a simple output in a new file containing 3 columns:
label max(c2 c3) max(c4 c5 c6)
where max is the maximum numerical value of columns 2-3 and 4-6.
I have been trying to do it with awk but somehow don't manage to get the syntax right...
Many thanks for your time and help!
KS
rdrtx1
September 6, 2017, 10:49am
2
awk '
{
($(NF-1) > $(NF)) ? _ : ($(NF-1)=$(NF)) ; NF--;
($(NF-1) > $(NF)) ? _ : ($(NF-1)=$(NF)) ; NF--;
max2=$NF ; NF--;
($(NF-1) > $(NF)) ? _ : ($(NF-1)=$(NF)) ; NF--;
($(NF-1) > $(NF)) ? _ : ($(NF-1)=$(NF)) ; NF--;
$0=$0 OFS max2;
print $0;
}
' OFS="\t" infile
ksennin
September 6, 2017, 11:07am
3
Thank you very much for your fast reply!
I tried and it seems that it doesn't work on my data: I just get calculations at the end of the output that don't really seem to make sense.
Could you please detail the code so I can investigate? Thank you very much
---------- Post updated at 03:07 PM ---------- Previous update was at 02:57 PM ----------
I thought I would give a more concrete example of my problem.
My input file is as follows:
label1 0 0 0 0 0 1
label2 0 0 0 0 0 1
label3 0.2 0.2 0.9 0 0 0
label4 0 0 0.8 0.1 0 0
label5 0.1 0.1 0.1 0.15 0.1 0.1
label6 0.1 0.15 0.1 0.1 0.1 0.1
with column 1 being a header of the row, and columns 2 to 7 being numerical values.
The output I would like is:
label1 0 1
label2 0 1
label3 0.9 0
label4 0.8 0.1
label5 0.1 0.15
label6 0.15 0.1
with:
column 1 = column 1 from the input
column 2 = maximum value of columns 2 to 4 from the input
column 3 = maximum value of columns 5 to 7 from the input
Many thanks!!
Thanks to the example things are clear now.
#!/bin/sh
awk '
function maxcol(startcol,endcol){
_maxcol=$startcol
while (++startcol<=endcol) {
if ($startcol>_maxcol) _maxcol=$startcol
}
return _maxcol
}
{ print $1, maxcol(2,4), maxcol(5,7) }
' infile
1 Like
ksennin
September 6, 2017, 11:58am
5
Many thanks, it works perfectly!!!