Finding the most positive and negative value and defining its position

Hi,

I have a file that looks like this:

Jake      2  3  4  6  4  3  -2  -1
Jerry     1  2  3  2  1  7  -6  -1
Timmy   -1  -4  -5  -8  9  3  1

I want to find the most positive and negative value for each row and also define its position (based on column #)

So the output would look something like:

Jake  6  4  -2  7
Jerry  7  6  -6  7
Timmy  9  5  -8  4

Where the first column is name, 2nd column is the most positive value, 3rd is its column position, 4th column is the most negative value and 5th column is the column position of the most negative value.

thanks

awk '{for(i=1;++i<=NF;){if($i>a){a=$i;b=(i-1)};if($i<c){c=$i;d=(i-1)}}}{print $1,a,b,c,d}' file

does not work. For the test data it does not go through it row by row instead it stalls at the first row.

If you want to use perl

cat  filename | perl -e 'while (<>){
chomp;
my ($name,@numbers) = split("\ ");
my ($max,$min,$max_pos,$min_pos) = (0,0,0,0);
for (my $i=0;$i<=$#numbers;$i++){
if ($numbers[$i] > $max){
($max,$max_pos) = ($numbers[$i],$i+1);
}
elsif ($numbers[$i] < $min){
($min,$min_pos) = ($numbers[$i],$i+1);
}
}
print "$name\t$max\t$max_pos\t$min\t$min_pos\n";
}
 '

Jake    6       4       -2      7
Jerry   7       6       -6      7
Timmy   9       5       -8      4

HTH,
PL

That's not very useful, state your OS, shall and maybe we will be able to solve your problem.

Try this:

awk '{
max=0;min=0
for(i=2;i<=NF;i++) {
   if ( max < $i ) {max=$i;maxpos=i-1}
   if ( min > $i ) {min=$i;minpos=i-1}
   if (i == NF) { print $1,max,maxpos,min,minpos}
}
}
' filename

Jake 6 4 -2 7
Jerry 7 6 -6 7
Timmy 9 5 -8 4

cheers,
Devaraj Takhellambam

And yet another Perl solution:

$ 
$ 
$ cat f2
Jake      2  3  4  6  4  3  -2  -1
Jerry     1  2  3  2  1  7  -6  -1
Timmy     -1  -4  -5  -8  9  3  1
$ 
$ 
$ perl -lne '/^(\w+[ ]+)(.*?)$/;@x=split/[ ]+/,$2; for(1..$#x){$x[$i]>$x[$_] or $i=$_; $x[$j]<$x[$_] or $j=$_} print "$1 $x[$i] ",$i+1," $x[$j] ",$j+1' f2
Jake       6 4 -2 7
Jerry      7 6 -6 7
Timmy      9 5 -8 4
$ 
$ 

tyler_durden

Hi, I tried all teh solutions and no matter what I put in as the input, the answer is always the same. I get something like

1 1
1 1
1 1
.....