Last active
September 10, 2018 14:01
-
-
Save kohlerdominik/c37bb094e5325176492bcb257d381253 to your computer and use it in GitHub Desktop.
Find Min, Max, Avg and Sum of column with a simple input. See usage example for more information
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/awk -f | |
# Usage example: | |
# get all of first column: ./minmax awk data.txt | |
# set a custom field separator (default: ,): ./minmax.awk -v fs=":" data.txt | |
# get all of the fourth column: ./minmax.awk -v column="4" data.txt | |
# get min of the first column: ./minmax.awk -v type="min" data.txt | |
# get min of the fourth column: ./minmax.awk -v column="4" -v type="min" data.txt | |
# | |
# valid "column": 1..no | |
# valid "type": min, max, avg, sum | |
BEGIN { | |
# set field separator | |
if (fs) | |
FS=fs | |
else | |
FS=","; | |
} | |
!i++ { | |
# reset variables on first match. | |
min = 9999; max = 0; sum = 0; | |
} | |
{ | |
value = $column | |
min = (min < value) ? min : value | |
max = (max > value) ? max : value | |
sum = (sum + value) | |
} | |
END { | |
# reset min if no match | |
min = (min == 9999) ? 0 : min | |
# calculate average | |
avg = sum / NR | |
#return requests value | |
if (type == "min") | |
print min | |
else if (type == "max") | |
print max | |
else if (type == "avg") | |
print avg | |
else if (type == "sum") | |
print sum | |
else | |
printf "min:%.2f;max:%.2f;avg:%.2f;sum:%.2f;", min, max, avg, sum | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment