Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash: Sum fields of a line

Tags:

bash

awk

I have a file with the following format:

a 1 2 3 4
b 7 8
c 120

I want it to be parsed into:

a 10
b 15
c 120

I know this can be easily done with awk, but I'm not familiar with the syntax and can't get it to work for me.

Thanks for any help

like image 357
Mugen Avatar asked Jan 27 '26 04:01

Mugen


1 Answers

ok simple awk primer:

awk '{ for (i=2;i<=NF;i++) { total+=$i }; print $1,total; total=0 }' file

NF is an internal variable that is reset on each line and is equal to the number of fields on that line so

for (i=2;i<=NF;i++) starts a for loop starting at 2

total+=$i means the var total has the value of the i'th field added to it. and is performed for each iteration of the loop above.

print $1,total prints the 1st field followed by the contents of OFS variable (space by default) then the total for that line.

total=0 resets the totals var ready for the next iteration.

all of the above is done on each line of input.

For more info see grymoires intro here

like image 161
peteches Avatar answered Jan 29 '26 18:01

peteches