conradlee conradlee - 1 year ago 118
Bash Question

Shell script: find maximum value in a sequence of integers without sorting

I have a file with a long list of integers:


I want to find the maximum value using UNIX command line tools. I know I can use
(and indeed there are solutions to this problem on SO that use
), but that's inefficient, requiring O(N*log(N)) and plenty of memory. With a simple for loop, I should be able to find the maximum value in O(N) and a couple of bytes of memory.

It seems there must be some program out there (with a name like
) that does this out of the box---is that true?

kev kev
Answer Source

Try this:

awk '$0>x{x=$0};END{print x}' input.txt


awk 'BEGIN{x=-2147483648};$0>x{x=$0};END{print x}' input.txt

Initializing x allows the solution to properly handle integer lists with values <= 0. See comments for more details.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download