简体   繁体   中英

Bash: how to sum all columns excluding first column

I need to sum all columns except the first column in a bash script. 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.

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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