- 论坛徽章:
- 0
|
实际工作中经常需要对一些数据列表进行相应的处理,比如,求和,最大/最小值,平均值等。 bash脚本中的expr只能处理简单整数的四则运算,不能处理浮点数据。在这种情况下,可以考虑bash脚本中嵌入另一种计算语言bc来增强数据统计功能。
下例中,假设,数据源的格式为简单的,
....
234.02
3345.05
12.4039
....
#!/bin/bash
##################################
##
##Desc: noramlly, in bash script by using
##arithmetical command "expr", the integer
##values can be operated. However, if other
##data types(float, double) are in data source, there would
##be problem by calling "expr", therefore, another
##script language bc has to be used to perform
##such operation.
##
##Argument: 1.)-sum(summary)/-min(minimum)/-max(maximum)/-ave(average)
## 2.)file name (data source)
##
##
###################
##Sum()
##Calculate sum
##of all data entries in
##data source
##
Sum()
{
echo "sum entries..."
tmp=0
for i in `cat $DATA`; do
tmp=`echo $tmp '+' $i | bc -l `
LINECNT=`expr $LINECNT + 1`
done
echo "----------------------"
echo "Sum: " $tmp "Nr of Entry:" $LINECNT
SUMVAL=$tmp
}
####################
##Max()
##Evaluate all data entry
##and find maximum one
##
Max()
{
echo "maximum..."
tmp=0
cmp=0
for i in `cat $DATA`; do
#compare,result saved in cmp
cmp=`echo $tmp '>' $i | bc -l`
#if necessary, exchange the maximum value
if [ $cmp -ne 1 ];then
tmp=$i
fi
done
echo "-----------------------"
echo "Max: " $tmp
}
#####################
##Min()
##Evaluate all data and
##find the minimum value
##
Min()
{
echo "minimum..."
tmp=0
cmp=0
cnt=0
for i in `cat $DATA`; do
#keep first data entry
cnt=`expr $cnt + 1`
if [ $cnt -eq 1 ];then
tmp=$i
continue
fi
#compare,result saved in cmp
cmp=`echo $tmp '>' $i | bc -l`
#if necessary, exchange the maximum value
if [ $cmp -ne 0 ];then
tmp=$i
fi
done
echo "-----------------------"
echo "Min: " $tmp
}
#####################
##Avg()
##calculate the average
##value of all data entries
##
Avg()
{
LINECNT=0
Sum
echo "Total Entries: "$LINECNT
tmp=0
tmp=`echo $SUMVAL '/' $LINECNT | bc -l`
echo "------------------------"
echo "Average: " $tmp
}
#####################
##Help()
##dispaly help information
##
##
Help()
{
echo "--------------------"
echo "Options: "
echo "1.) -sum/-max/-min/ave: to calculate summary/maximum/minimun/average values"
echo "2.)file name if necessary with path. "
echo "--------------------"
}
#####################
## Programm Entry
## from here
##
echo "Staring evaluating..."
##check argument
if [ $# -ne 2 ]; then
echo ""
echo "Missing argument ..."
echo ""
Help
exit
fi
##check file
if ! test -f $2; then
#echo "Given file is existing !"
#exit
#else
echo "Given file is not existing !"
exit
fi
DATA=$2
LINECNT=0
LINECNT=0
##do calculation
case "$1" in
"-sum")
Sum
;;
"-min")
Min
;;
"-max")
Max
;;
"-ave")
Avg
;;
*)
echo "Unkonw argument"
Help
;;
esac
本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u1/45602/showart_409583.html |
|