[英]Unix bash scripting sort
i need help to calculate and display the largest and average of a group of input numbers. 我需要帮助来计算和显示一组输入数字的最大和平均值。
The program should accept a group of numbers, each can be up to 3 digits. 该程序应接受一组数字,每个数字最多3位。
For example, input of 246, 321, 16, 10, 12345, 4, 274 and 0 should result in 321 as the largest and the average of 145, with an error message indicating that 12345 is invalid. 例如,输入246、321、16、10、12345、4、274和0应该导致321最大,而平均值为145,并显示一条错误消息,指出12345无效。
Any ideas how to sort in bash ? 任何想法如何在bash中排序? Sorry I am not developer in this low level, any help is great :)
抱歉,我不是一个低水平的开发人员,任何帮助都很棒:)
I see that you ask for a Bash
solution but since you tagged it also Unix
I suggest a pure awk
solution ( awk
is just ideal for such problems): 我看到您要求一个
Bash
解决方案,但是由于您在Unix
也对其进行了标记,因此我建议使用纯awk
解决方案( awk
对于此类问题非常理想):
awk '
{
if(length($1) <= 3 && $1 ~ /^[0-9]+$/) {
if($1 > MAX) {MAX = $1}
SUM+=$1
N++
print $1, N, SUM
} else {
print "Illegal Input " $1
}
}
END {
print "Average: " SUM / N
print "Max: " MAX
}
' < <(echo -e "246\n321\n16\n10\n12345\n4\n274\n0")
prints 版画
246 1 246
321 2 567
16 3 583
10 4 593
Illegal Input 12345
4 5 597
274 6 871
0 7 871
Average: 124.429
Max: 321
However, I cannot comprehend why the above input yields 145 as average? 但是,我不明白为什么上面的输入平均产生145?
tmpfile=`mktemp`
while read line ; do
if [[ $line =~ ^[0-9]{1,3}$ ]] ; then
# valid input
if [ $line == "0" ] ; then
break
fi
echo $line >> $tmpfile
else
echo "ERROR: invalid input '$line'"
fi
done
awk ' { tot += $1; if (max < $1) max = $1; } \
END { print tot / NR; print max; } ' $tmpfile
rm $tmpfile
A piped coreutils
option with bc
: 带有
bc
管道化coreutils
选项:
echo 246 321 16 10 12345 4 274 0 \
| grep -o '\b[0-9]{1,3}\b' \
| tee >(sort -n | tail -n1 > /tmp/max) \
| tr '\n' ' ' \
| tee >(sed 's/ $//; s/ \+/+/g' > /tmp/add) \
>(wc -w > /tmp/len) > /dev/null
printf "Max: %d, Min: %.2f\n" \
$(< /tmp/max) \
$((echo -n '('; cat /tmp/add; echo -n ')/'; cat /tmp/len) | bc -l)
Output: 输出:
Max: 321, Min: 124.43
grep
ensures that the number format constraint. grep
确保数字格式约束。 sort
finds max, as suggested by chepner sort
chepner的建议, sort
找到最大值 sed
and wc
generate the sum and divisor. sed
和wc
生成总和和除数。 Note that this generates 3 temporary files: /tmp/{max,add,len}
, so you might want to use mktemp
and/or deletion: 请注意,这会生成3个临时文件:
/tmp/{max,add,len}
,因此您可能要使用mktemp
和/或delete:
rm /tmp/{max,add,len}
Stick this into the front of the pipe if you want to know about invalid input: 如果您想了解无效输入,请将其粘贴到管道的前面:
tee >(tr ' ' '\n' \
| grep -v '\b.{1,3}\b' \
| sed 's/^/Invalid input: /' > /tmp/err)
And do cat /tmp/err
after the printf
. 然后在
printf
之后执行cat /tmp/err
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.