AWK - 需要显示字段总值和字段编号

AWK - 需要显示字段总值和字段编号

我有下面的数据需要计算或总计从特定字段开始的值。计算所需字段下方的示例来自 Field5。对于示例,Field5 总计为 42,field6 总计为 107,依此类推。

输入文件:

A,B,C,D,42,52,23,101,5,1,0,0,0
A,B,C,D,0,52,3,0,5,0,0,0,0
A,B,C,D,0,1,4,0,4,0,0,0,0
A,B,C,D,0,2,2,0,1,0,0,0,0

预期输出:

Field5=42, Field6=107, Field7=32, Field8=101, Field9=15, Field10=1

尝试使用这段代码,我知道它是错误的。哈哈

echo "A,B,C,D,42,52,23,101,5,1,0,0,0
A,B,C,D,0,52,3,0,5,0,0,0,0
A,B,C,D,0,1,4,0,4,0,0,0,0
A,B,C,D,0,2,2,0,1,0,0,0,0" | awk -F"," '{for(i=0;i<=NF;i++){C++}} END {print i"=" C}'

答案1

您可以使用:

awk -F"," '{for (i=5;i<=NF;i++){a[i]=a[i]+$i}} END { for (i in a){ print "Field" i "=" a[i]}}' file

在你的情况下它会打印

Field5=42
Field6=107
Field7=32
Field8=101
Field9=15
Field10=1
Field11=0
Field12=0
Field13=0

答案2

尝试使用下面的 awk,它就像一个魅力;命令是:

j=`awk -F ","  '{print NF}' filename| sort -nr| sed -n '1p'`
for ((i=5;i<=$j;i++)); do awk -v i="$i" -F "," 'BEGIN{sum=0}{sum=sum+$i}END {print "Field"i"=" sum}' filename; done| perl -pne "s/\n/, /g"

输出:

Field5=42, Field6=107, Field7=32, Field8=101, Field9=15, Field10=1, Field11=0, Field12=0, Field13=0

相关内容