conradlee
conradlee

Reputation: 13695

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

I have a file with a long list of integers:

10
4
66
....

I want to find the maximum value using UNIX command line tools. I know I can use sort (and indeed there are solutions to this problem on SO that use sort), 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 max) that does this out of the box---is that true?

Upvotes: 11

Views: 29034

Answers (4)

kev
kev

Reputation: 161684

You can use this if no negative number is expected:

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

Use this to support negative numbers:

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 the comments for more details.

Upvotes: 28

Koushik Karmakar
Koushik Karmakar

Reputation: 11

sort -nr inputfile.txt | head -1 where inputfile.txt contains all numbers.

Upvotes: -1

Vijay
Vijay

Reputation: 67231

awk '{if($1>a)a=$1;}END{print a}' temp3

Upvotes: 1

Sebi
Sebi

Reputation: 4522

 max=1

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

 echo "$max" > b.txt

a.txt is the input file(with an integer on each line). b.txt contains the maximum of the integers in a.txt.

Upvotes: 1

Related Questions