文件:
Name: Rad
Eng: 94
Tam: 98
Mat: 98
Soc: 98
Sci: 80
Name: Din
Eng: 87
Tam: 89
Mat: 78
Soc: 87
Sci: 34
Name: Hardy
Eng: 78
Tam: 87
Mat: 23
Soc: 34
Sci: 98
剧本 :
#!/bin/bash
file=$1
num=$2
n=`wc -l < $file`
it=$((n/num))
echo $n
echo $it
awk -v numm="$num" '{if (NR<=numm){T+=$2}}END{print T}' $file
我上面的脚本可以为第一个学生生成总数。 我也想找到剩余的两个学生成绩的总数。 有人可以帮我弄这个吗?
You can search for
Name
and every time is found you go to the nextnumm
lines and sum the scores:结果:
请找到以下命令以实现相同
命令:
输出
结果:
The first
awk
block is executed for each line that starts with the stringName:
. If thename
variable has a value, then the summed up score for the previous student is printed along with the student's name. Then the name is set to the second field of the current line and the score is reset to zero. The script then immediately continues with the next input line.The second block is executed for every row of input that is not handled by the previous block. It simply adds the score to the value of the
score
variable.最后一个块在读取文件的最后一行之后执行,并模仿在第一个块中完成的输出。这样可以输出最后一个学生的成绩。
复制代码很难看,因此这是一个使用函数执行输出的解决方案:
这不是问题的一部分,但可能很有趣:
输出: