Friday, January 07, 2011

Bash: Find the Max in a list of Integers

Max is a little shells script that will find the maximum value and returns that value and the line it was found at.

max
#!/bin/bash
MAX=0
ELE=0
while read line; do
ELE=$[ $ELE + 1 ]
if [ "$line" -gt "$MAX" ]; then
MAX=$line
POS=$ELE
fi
done
echo "$MAX $POS"

Usage Example
-bash-3.2$ cat ttt
1000000001
1000000000002
1000000000007
1000000000033
9999
1000000000000
1000000000005
-bash-3.2$ ./max < ttt
1000000000033 4
-bash-3.2$

No comments: