简体   繁体   English

Bash:如何将除第一列之外的所有列相加

[英]Bash: how to sum all columns excluding first column

I need to sum all columns except the first column in a bash script. 我需要在bash脚本中对除第一列之外的所有列求和。 Please help as I am a beginner in scripting. 请帮忙,因为我是脚本编写的初学者。

COL1    COL2    COL3    COL4    COL5

APR     674070  672554  813355  809413
APR     674070  672554  813355  809413
APR     674070  672554  813355  809413
APR     375309  374466  460572  457776
APR     254161  253655  316361  314093
APR     234389  233874  295457  293222
APR     252482  251926  319122  316918

The output should look like below. 输出应如下所示。 The first column (ie, APR) is same for all rows and I don't need to bother printing it. 第一列(即APR)对于所有行都是相同的,我不需要打扰它。

The desired result is either 期望的结果是

APR,3138551,3131583,3831577,3810248

or 要么

3138551,3131583,3831577,3810248

I tried the command below, but I will require more than 20 columns and my method will be too lengthy with that many columns. 我尝试了下面的命令,但是我需要超过20列,而且我的方法对于那么多列来说太长了。

cat file | awk -F ',' '{a=a+$2}{b=b+$3}{c=c+$4}{d=d+$5} END { print "APR"","a","b","c","d }'

Let me know if exists an alternate way in bash. 如果在bash中存在另一种方式,请告诉我。

awk -F"," '{for(i=2; i<=NF; i++) sum[i]+=$i} END {for (i=2;i<=NF;i++)if(i!=NF) printf "%d, ",sum[i]; else print sum[i]}' file

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM