Reputation: 53
function greater {
grep -Eo '[0-9]*' $1 | sort -rn | head -n 1
}
function lesser {
grep -Eo '\-[0-9]*' $1 | sort -n | head -n 1
}
I've made these functions, but the negative numbers are being printed: the first function is ignoring the - sign, so it is showing the greatest number, but it should print the greatest positive. Any ideas on how to solve that?
Sample input:
-100 -90 95
10 -20
500 400 300 200 600
Sample output:
Greater: 600
Lesser: -100
(The lesser is working perfectly.)
Upvotes: 2
Views: 69
Reputation: 67467
extending your approach
$ tr -s ' ' \\n <file | sort -n | sed -n '1s/.*/min: &/p;$s/.*/max: &/p'
min: -100
max: 600
Upvotes: 0
Reputation: 203349
Using any awk alone:
awk '
NR==1 { min=max=$1 }
{ for (i=1; i<=NF; i++) {if ($i<min) min=$i; if (max<$i) max=$i} }
END { printf "Greater: %d\nLesser: %d\n", max, min }
' file
Greater: 600
Lesser: -100
The printfs with %d
ensure you'll get numeric output even if the input file is empty.
Upvotes: 1
Reputation: 785088
I would suggest instead of using grep + sort | head
twice, it would be more efficient to use gnu awk
and get both max
and min
in a single command:
awk -v RS='[[:space:]]+' '
NR==1 {max=min=$1}
$1 > max {max=$1}
min > $1 {min=$1}
END {print "max=" max, "min=" min}' file
max=600 min=-100
Where file
data is:
cat file
-100 -90 95
10 -20
500 400 300 200 600
Or using any version awk
:
tr '[[:blank:]]' '\n' < file |
awk 'NR==1{max=min=$1} $1 > max {max=$1} min > $1 {min=$1} END {print "max=" max, "min=" min}'
Upvotes: 3
Reputation: 133458
With your shown samples, you could try following also. Simple explanation would be; using xargs to print all elements in 1 column, then passing it to awk
as a standard input, where finding the minimum and maximum values by reading whole Input_file at END block of program printing both the values there.
xargs -n1 < Input_file | awk 'FNR==1{max=min=$0} max>$0{max=$0} min<$0{min=$0} END{print max,min}'
Above reads values from Input_file in case you want to read it from a shell variable then try following(where var
is shell variable):
xargs -n1 <<< "$var" | awk 'FNR==1{max=min=$0} max>$0{max=$0} min<$0{min=$0} END{print max,min}'
Upvotes: 3