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?
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It only takes a minute to sign up.
Sign up to join this communityAssuming 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
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
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