QQ登录

只需一步,快速开始

 找回密码
 注册

QQ登录

只需一步,快速开始

查看: 1145|回复: 2

弱问一个shell编程题

[复制链接]
发表于 2006-4-19 20:05:58 | 显示全部楼层 |阅读模式
假设score.txt文件中保存了三个班级的学生考试成绩,请写一个shell程序计算每个班级的学生人数与平均分
假设 文件中保存的内容格式为
班级            姓名            成绩
01/02/03      张三            98

我有几个不明白的地方 怎么样将匹配的字符转化为数字赋值给一个变量用来计算
各位大侠有空帮我写一个 我初学shell 想好好参考
谢谢
发表于 2006-4-20 18:02:00 | 显示全部楼层
下面是我写的一个脚本文件,你可以试一下:
[code:1]
#!/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
[/code:1]
说明:脚本文件共有三个参数,参数1为保存数据的文件名, 参数2为要查询的班级名称,参数3为成绩所在的列.如果脚本名称为test,你可以通过(/path/test 数据文件名 班级名称 成绩所在列序号)的方式调用,例:
/path/test datafile 一班 3
数据文件各栏目之间请用tab符号隔开.[/code]
回复

使用道具 举报

 楼主| 发表于 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"
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则

GMT+8, 2024-6-29 08:56 , Processed in 0.073761 second(s), 15 queries .

© 2021 Powered by Discuz! X3.5.

快速回复 返回顶部 返回列表