2

I have a file with a table of numbers; the first line is a header line. I want to sum each column and print out sum and column name for each column using awk.

How can I do it?

1
  • This question needs example input and output. It's unclear otherwise.
    – Sparhawk
    May 27, 2019 at 22:32

1 Answer 1

5

Assuming that every line has the same number of fields (columns):

awk '
    NR==1   { for (i=1; i<=NF; i++) header[i]=$i; next; }
            { for (i=1; i<=NF; i++) total[i] += $i; }
    END     { for (i=1; i<=NF; i++) print header[i] "=" total[i]+0 }
    '

Sample input:

red green blue
1 2 4
8 16 32
64 128 256

Corresponding output:

red=73
green=146
blue=292
3
  • One small improvement: on line 1 set n=NF then, everywhere, loop until i<=n -- that will cover the case where there are too many headers, and the output will include extra_header=0 May 21, 2019 at 22:48
  • I was considering various approaches to handling badly formed input; capturing the number of headers was one of them.  But I’m not 100% sure that I understand your comment.   ISTM that setting n=NF when NR==1 is mostly good for guarding against the last line of input having too few fields.  And, if I take your suggestion, and the input has 42 headers, then my script will iterate over 42 fields even on lines that don’t have that many.  I believe that capturing the maximum NF would be more robust. May 22, 2019 at 0:48
  • IMO you want a count for each header, so NF on line 1 will drive the counting. I don't know what we would want to output for lines with too many fields. May 22, 2019 at 1:24

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .