计算shell脚本中每一行的平均和

我是Shell脚本的新手,我需要一些帮助:

我具有以下输入格式:

x,x,12,4,61,1,9
y,y,13,62,2,9
z,z,11,9
c,c,60,3,9

我想为每行显示平均和和第一个单词,例如:

x x : 17.4
y y: 18
...

到目前为止,我的代码如下:

#!/bin/sh

while IFS= read -r line; do
echo "$line"
done < "input.txt"

但是我不知道如何处理每一行

syldjzl88888 回答:计算shell脚本中每一行的平均和

如果您使用awk,它将为您循环记录:

$ awk -F,'{                    # set input field delimiter
    for(i=3;i<=NF;i++)          # iterate values starting from 3rd field 
        sum+=$i                 # sum up the values
    print $1,$2,":",sum/(NF-2)  # output
    sum=0
}' file

输出:

x x : 17.4
y y : 18
z z : 17.2
c c : 17.4

如果您想知道NF

NF

    The number of fields in the current input record. 
    NF is set each time a new record is read,when a new field is created,or when $0 changes 
本文链接:https://www.f2er.com/3100551.html

大家都在问