猿问

AWK脚本,如果column1中的值重复,则求和多列

需要您的帮助来解决以下查询。我想总结column3,column5,column6,column7,column9,column10的值(如果column1中的值重复)。还需要在输出文件中将重复的行作为单行,并且还需要将column1的值放在输出文件的第8列中


输入文件


a|b|c|d|e|f|g|h|i|j

IN27201800024099|a|2.01|ad|5|56|6|rr|1|5

IN27201800023963|b|3|4|rt|67|6|61|ty|6

IN27201800024099|a|4|87|ad|5|6|1|rr|7.45

IN27201800024099|a|5|98|ad|5|6|1|rr|8

IN27201800023963|b|7|7|rt|5|5|1|ty|56

IN27201800024098|f|80|67|ty|6|6|1|4rght|765

输出文件


a|b|c|d|e|f|g|h|i|j|k

IN27201800024099|a|11.01|190|ad|66|18|3|rr|20.45|IN27201800024099

IN27201800023963|b|10|11|rt|72|11|62|ty|62|IN27201800023963

IN27201800024098|f|80|67|ty|6|6|1|4rght|765|IN27201800024098

在下面的代码中尝试过,但是它不起作用,也不知道如何完成代码以获取正确的输出


awk 'BEGIN {FS=OFS="|"} FNR==1 {a[$1]+= (f3[key]+=$3;f5[key]+=$5;f6[key]+=$6;f7[key]+=$7;f9[key]+=$9;f10[key]+=$10;)} input.txt > output.txt


慕莱坞森
浏览 317回答 1
1回答

摇曳的蔷薇

$ cat tst.awkBEGIN {&nbsp; &nbsp; FS=OFS="|"}NR==1 {&nbsp; &nbsp; print $0, "h"&nbsp; &nbsp; next}{&nbsp; &nbsp; keys[$1]&nbsp; &nbsp; for (i=2; i<=NF; i++) {&nbsp; &nbsp; &nbsp; &nbsp; sum[$1,i] += $i&nbsp; &nbsp; }}END {&nbsp; &nbsp; for (key in keys) {&nbsp; &nbsp; &nbsp; &nbsp; printf "%s", key&nbsp; &nbsp; &nbsp; &nbsp; for (i=2; i<=NF; i++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; printf "%s%s", OFS, sum[key,i]&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; print OFS key&nbsp; &nbsp; }}$ awk -f tst.awk filea|b|c|d|e|f|g|hIN27201800023963|10|11|72|11|62|62|IN27201800023963IN27201800024098|80|67|6|0|1|765|IN27201800024098IN27201800024099|11.01|190|66|18|3|20.45|IN27201800024099上面的代码以随机顺序输出行,如果您希望它们以与读入键值相同的顺序输出,那只是几行代码:$ cat tst.awkBEGIN {&nbsp; &nbsp; FS=OFS="|"}NR==1 {&nbsp; &nbsp; print $0, "h"&nbsp; &nbsp; next}!seen[$1]++ {&nbsp; &nbsp; keys[++numKeys] = $1}{&nbsp; &nbsp; for (i=2; i<=NF; i++) {&nbsp; &nbsp; &nbsp; &nbsp; sum[$1,i] += $i&nbsp; &nbsp; }}END {&nbsp; &nbsp; for (keyNr=1; keyNr<=numKeys; keyNr++) {&nbsp; &nbsp; &nbsp; &nbsp; key = keys[keyNr]&nbsp; &nbsp; &nbsp; &nbsp; printf "%s", key&nbsp; &nbsp; &nbsp; &nbsp; for (i=2; i<=NF; i++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; printf "%s%s", OFS, sum[key,i]&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; print OFS key&nbsp; &nbsp; }}$ awk -f tst.awk filea|b|c|d|e|f|g|hIN27201800024099|11.01|190|66|18|3|20.45|IN27201800024099IN27201800023963|10|11|72|11|62|62|IN27201800023963IN27201800024098|80|67|6|0|1|765|IN27201800024098
随时随地看视频慕课网APP
我要回答