find max number

Hi, i have a file with numbers in it and i was wondering if there's a script i could use to find the max number and have that printed to a new file?

example a.txt

18
26
47
34
27

so find the max number in a.txt and print it to b.txt.

Thanks!

man sort

awk 'n < $0 {n=$0}END{print n}' a.txt > b.txt

Please read the Forum rules and don't ask homework questions.

you can simply use the for loop and get the max no. out of the file: as:

max=1

for in `cat a.txt`
do
if [[ $1 > "$max" ]]; then
max=$1
echo "$max" > b.txt
fi
done

Hope this will work to you.
Thanks
Varun Gupta:b:

The echo statement must be after the loop and avoid the useless use of cat:

max=1

while read i
do
  if [[ "$i" > "$max" ]]; then
    max="$1"
  fi
done < a.txt

echo "$max" > b.txt

Regards

sort -r file | head -1 > newfile

You should use the -n option to sort numeric values:

sort -nr file | head -1 > newfile

Regards

sort -r will display the result in reverse order... it can be used for sorting numeric values also.. and this cmd seems to be working fine for me...

cat file.txt | sort -r

47
34
27
26
18

Why exactly do you need a cat here?

Just for giving input to sort or else we can use this:

sort -r file.txt

i dont think there is any differnce b/w above one and the earlier command i posted... if there is any pls point it out...

Am more than happy to receive comments...:slight_smile:

Just follow the posted link.

The -n for numeric sort is important.
If "file" contains:
1
10
100
2
20
200
3
30
300

sort -r file
300
30
3
200
20
2
100
10
1

sort -nr file
300
200
100
30
20
10
3
2
1

Thanks methyl... got the difference...

cheers mate....

and if you only want the highest number output...
use tail -n 1 (to get the last one).

[user@host ~]$ sort -n lines.txt
1
2
3
4
9
12
32
45
50

[user@host ~]$ sort -n lines.txt |tail -n 1
50

What if i have some similar numbers?
for example
20
35
100
70
30
100
if i sort these numbers i wll have 100 two times at the top.what if i want to get both '100s'?

//suppose i do this to many files so i dont know what the input is,i just want to get the biggest number(s) in each file...

I know there's easier ways to do this, but this should get you started.
This will get the highest number(s) in the file.

large=0
sort -rn FILE.TXT | while read line
do
top="$line"
if [ "$top" -gt "large" -o "$top" -eq "$large" ]
then
  echo "$top"
  large="$top"
fi
done

Franklin52's solutions work fine.

you can also go for

sort -n ref_file | tail -1 > new_file

thnks a lot guys i' m going to check these right away;)