Calc max of a column

In C that was easy with a for and if. Iam trying to learn a litle more in bash.

Example

Ronaldo:5800
Figo:4000
Rafael:2321
Kaka:1230

I want the max of the $2 and the output will be:

The max value is 5800 from Ronaldo.

How can i do this in shell?
Thanks for all, folks.

$
$ cat f2
Ronaldo:5800
Figo:4000
Rafael:2321
Kaka:1230
$
$ cat f2.sh
#!/usr/bin/bash
IFS=:
while read name amt
do
  [[ "$amt" -ge "${MAX}" ]] && MAX=$amt
done <f2
echo "Max value = $MAX"
$
$ ./f2.sh
Max value = 5800
$
$

tyler_durden

I am getting the content from file.sh

name:price
Ronaldo:5800
Figo:4000
Rafael:2321
Kaka:1230

I write this..

while read name price
do
  [[ "$price" -ge "${MAX}" ]] && MAX=$price
done <$price
echo "Max value = $MAX" ;

The error..

./file.sh: line 29: $price: ambiguous redirect

You will have to redirect from your data file, not from a value of a variable.

tyler_durden

$ sort -t":" -knr2 file | IFS=":" read x y
$ echo $y
5800
awk -F":" ' $2>s{s=$2} END{print s} ' file

Look at durden_tyler's code more closely. It sets IFS to the value necessary to properly split the lines with read. It looks like you omitted the IFS modification. If so, without any whitespace in the line, the entire line (sans leading whitespace) will be assigned to $name. $price will be empty.

Also, as he mentioned above, you're trying to redirect from the wrong place. $price does not contain the name of the file to read.

Regards,
Alister

awk -F":" ' $2>s{s=$2} END{print s} ' file

[/quote]

In this case, the result is the print of my first line of the text, that is name : price. how can i make the prog to start read in second line?

file.sh
name : price
Ronaldo:5800
Figo:4000
Rafael:2321
Kaka:1230

sort -k 2,2 -nr -k1,1 -t":" filename |   awk -F ":" '{print "The max value is from " $2 " from " $1; exit}'

HTH,
PL

It gives me a different number that is the maximum.

(file.sh)
name:amount
aa:1000
bb:2000
cc:3000
gg:7000
dd:4000
ee:5000
ff:6000

The result must be 7000 right? but the sort gives me 6000. The result of the sort is

ff:6000
ee:5000
dd:4000
gg:7000..
name:amount

:frowning:

awk -F":" ' int($2)>s{s=$2;t=$1} END{printf "The max value is %s from %s.", s,t} ' file
sort -t: -k2,2nr file | cut -d: -f2 | head -n1

Test run:

$ cat file
name:amount
aa:1000
bb:2000
cc:3000
gg:7000
dd:4000
ee:5000
ff:6000

$ sort -t: -k2,2nr file | cut -d: -f2 | head -n1
7000

done! thanks :smiley:

another question..

to calculate the min in the column is:

awk -F":" ' int($2)<s{s=$2;t=$1} END{printf "The max value is %s from %s.", s,t} ' file

is this correct? i only changed the > to <..