首页 文章

BASH-计算同一行中某些字段的平均值

提问于
浏览
0

我有一个这种格式的文件:`

123456789 Lee Johnson 72 85 90
999999999 Jaime Smith 90 92 91
888111818 JC Forney 100 81 97
290010111 Terry Lee 100 99 100
199144454 Tracey Camp 77 84 84
299226663 Laney Camp 70 74 71
434401929 Skyler Camp 78 81 82
928441032 Jess Forester 85 80 82
928441032 Chris Forester 97 94 89`

我需要编写一个bash脚本来计算每个学生的平均成绩(字段4-6),然后输出如下:`

71 [299226663] Camp Laney
80 [434401929] Camp Skyler
81 [199144454] Camp Tracey
93 [928441032] Forester Chris
82 [928441032] Forester Jess
92 [888111818] Forney JC
82 [123456789] Johnson Lee
99 [290010111] Lee Terry
91 [999999999] Smith Jaime`

平均值是第一个字段(截断值),括号[]中的用户ID,然后排序顺序如下:姓氏(组织文件中的第3个字段),然后是名字(组织文件中的第2个字段),后跟用户ID(组织文件中的第一个字段)

注意:我已经使用awk编写了一个脚本来执行此操作,但我应该第二次使用W / O awk或Perl . 对我来说棘手的是能够在SAME行上计算特定字段,然后输出正确的格式 . 我该怎么办?

以下是使用awk作为参考的解决方案: awk '{sum = $4 + $5 + $6; avg = sum/3;print int(avg), "[" $1 "]", $3, $2}' $1 | sort -k3 -k4 -k2

1 回答

  • 0

    bash中的 read 将为您分割行,并允许类似于您的awk版本的解决方案 .

    从标准输入读取一行,第一个单词分配给第一个名称,第二个单词分配给第二个名称,依此类推,剩余单词及其间隔分隔符分配给姓氏 .

    $ cat rs.sh
    while read -r id first last s1 s2 s3
    do
        avg=$(((s1 + s2 + s3) / 3))
        printf "%d [%s] %s %s\n" $avg $id "$last" "$first";
    done
    
    $ cat rs.txt
    123456789 Lee Johnson 72 85 90
    999999999 Jaime Smith 90 92 91
    888111818 JC Forney 100 81 97
    290010111 Terry Lee 100 99 100
    199144454 Tracey Camp 77 84 84
    299226663 Laney Camp 70 74 71
    434401929 Skyler Camp 78 81 82
    928441032 Jess Forester 85 80 82
    928441032 Chris Forester 97 94 89
    
    $ sh rs.sh < rs.txt | sort -k3 -k4 -k2
    71 [299226663] Camp Laney
    80 [434401929] Camp Skyler
    81 [199144454] Camp Tracey
    93 [928441032] Forester Chris
    82 [928441032] Forester Jess
    92 [888111818] Forney JC
    82 [123456789] Johnson Lee
    99 [290010111] Lee Terry
    91 [999999999] Smith Jaime
    

相关问题