Skip to content

Instantly share code, notes, and snippets.

@hexaflexahexagon
Last active April 17, 2022 21:43
Show Gist options
  • Save hexaflexahexagon/66f093ebd861e60b28cd57efff5fc2c9 to your computer and use it in GitHub Desktop.
Save hexaflexahexagon/66f093ebd861e60b28cd57efff5fc2c9 to your computer and use it in GitHub Desktop.
# Read an input file and find the sum/count/average/median
#!/bin/bash
# Read an input file and find the sum/count/average/median
# ! Does not do any validation of the input !
FILE='numbers.txt' # where the file is just a list of numbers, one per line
# Read input file line-by-line
while IFS= read -r num; do
sum=$((sum + num))
count=$((count + 1))
done < "$FILE"
# Print results
printf "Count is %s\n" $count
printf "Sum is %s\n" $sum
# Use `bc` command to do float math with the average
printf "Average is %.2f\n" "$(bc -l <<< "$sum/$count")"
# Find median
if [[ $((count % 2)) == 1 ]]; then
# Odd number of lines
middle=$(( (count + 1) / 2))
median=$(head -n${middle} "$FILE" | tail -n1)
else
# Even number of lines
middle=$((count / 2))
medians=$(head -n${middle} "$FILE" | tail -n2)
first=$(echo $medians | cut -d' ' -f1)
second=$(echo $medians | cut -d' ' -f2)
median=$(bc -l <<< "$first+$second / 2")
fi
printf "Median is %.2f\n" "$median"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment