kkfly 发表于 2006-4-19 20:05:58

弱问一个shell编程题

假设score.txt文件中保存了三个班级的学生考试成绩,请写一个shell程序计算每个班级的学生人数与平均分
假设 文件中保存的内容格式为
班级            姓名            成绩
01/02/03      张三            98

我有几个不明白的地方 怎么样将匹配的字符转化为数字赋值给一个变量用来计算
各位大侠有空帮我写一个 我初学shell 想好好参考
谢谢

fxdlxf 发表于 2006-4-20 18:02:00

下面是我写的一个脚本文件,你可以试一下:

#!/bin/bash

FN_SRC=$1
FN_TMP=$FN_SRC.tmp
FN_COUNT=$FN_SRC.count

CLASS_NAME=$2
COL=$3

if [ "$FN_SRC" = "" ] || [ "$CLASS_NAME" = "" ] || [ "$COL" = "" ] ; then
echo 'Must param:Data file,class name,and col index.'
exit
fi

if [ -r "$FN_SRC" ]; then
[ -f $FN_TMP ] && rm -f $FN_TMP

grep -i "$CLASS_NAME" $FN_SRC | awk '{print $'$COL'}' > $FN_TMP

TOTAL=0
COUNT=0
AVG=0

while read ITEM
do
    TOTAL=`expr $TOTAL + $ITEM`
    COUNT=`expr $COUNT + 1`
done < $FN_TMP

AVG=`expr $TOTAL / $COUNT`

echo -e "Total:\t$TOTAL"
echo -e "Count:\t$COUNT"
echo -e"Avg:\t$AVG"
else
echo "File $FN_SRC can't Read..."
exit
fi

说明:脚本文件共有三个参数,参数1为保存数据的文件名, 参数2为要查询的班级名称,参数3为成绩所在的列.如果脚本名称为test,你可以通过(/path/test 数据文件名 班级名称 成绩所在列序号)的方式调用,例:
/path/test datafile 一班 3
数据文件各栏目之间请用tab符号隔开.

kkfly 发表于 2006-4-20 20:15:41

我自己写的一个脚本中间有错的地方不知道怎么改
我注释出来了请教怎么改
谢谢各位大侠了
#!/bin/sh
#课后练习最后一题,假设score.txt文件中的考试成绩给出的格式为
#                   班级       姓名      得分
#                   01         张三      50

      echo "Please input the class id(01/02/03) that you want to qurey:"
      read classid
      num=0
      totalscore=0
      avarage=0
      grep -c $classid score.txt>temp
      read num<temp
      rm temp
      echo "the students of class $classid is : $num"
      index=2
      score=null
      while[ "$score" != '' ]   #判断score是不是为空的 因为我用的是cut命令                              
                                     #有错误 应该怎么判断呢 ??
      do
                cut -f(3*index) socre.txt>temp#我想做得是截取n*3个域中的数字
                                                 #(根据内容格式)可是不知对不对
                read score<temp
                rm temp
                $index+=1
                totalscore=`expr $totalscore+$score`
      done
      avarage=`expr $totalscore/$num`
      echo "the avarage score of the student is :$avarage"
页: [1]
查看完整版本: 弱问一个shell编程题