我有一个带有ID和分数的学生名单,我需要用他们的平均分数做另一个。 main_list:
#name surname student_index_number course_group_id lecturer_id list_of_marks
athos musketeer 1 1 1 3,4,5,3.5
porthos musketeer 2 1 1 2,5,3.5
aramis musketeer 3 2 2 2,1,4,5
我有这个脚本
awk '{ n = split($6, a, ","); total=0; for (v in a) total += a[v]; print total / n }' main_list
但是我不想打印它,我想将它写在另一个文件中,称为平均值。最终内容应如下所示,average_list:
athos musketeer 1 1 1 3.875
porthos musketeer 2 1 1 3.5
aramis musketeer 3 2 2 3
答案 0 :(得分:1)
请您尝试一次。
while read first second third fourth fifth sixth
do
if [[ "$first" =~ (^#) ]]
then
continue
fi
count="${sixth//[^,]}"
val=$(echo "(${#count}+1)" | bc)
new_val=$(echo "scale=2; (${sixth//,/+})/$val" | bc)
echo "$first $second $third $fourth $fifth $new_val"
done < "Input_file" > "Output_file"
尝试尝试以下操作。
awk '{ n = split($6, a, ","); total=0; for (v in a) total += a[v]; print $1,$2,$3,$4,$5,total / n }' Input_file > "Output_file"
答案 1 :(得分:1)
使用awk:
awk '{n=split($NF,array,","); NF--; sum=0; for(i=1; i<=n; i++){sum+=array[i]} print $0,sum/n}' file
使用$NF
将最后一个字段(,
)拆分为一个数组(array
)。 n
包含许多元素。将当前行中的列数减少一(NF--
)。使用for循环添加数组内容,并输出当前行的其余部分($0
)和结果(sum/n
)
输出:
athos musketeer 1 1 1 3.875 porthos musketeer 2 1 1 3.5 aramis musketeer 3 2 2 3
请参阅:8 Powerful Awk Built-in Variables – FS, OFS, RS, ORS, NR, NF, FILENAME, FNR