Save the sum to a file called sum
, sorted
awk -F, '{a[$1]+=$3;}END{for (i in a)print i", "a[i];}' filename | sort > sum
cat sum
product_a, 515
product_b, 348
product_c, 495
product_d, 27
Join the two files, first column of first file with first column of second (think "keys"); pipe it to awk
and print reordered columns, using ,
as field separator (-F
) and as the Output Field Separator (-OFS
)
join -t ',' -1 1 -2 1 filename sum | awk -F, -OFS=, {'print $1,$4,$2,$3}'
product_a, 515, domestic, 500
product_a, 515, abroad, 15
product_b, 348, domestic, 313
product_b, 348, abroad, 35
product_c, 495, domestic, 411
product_c, 495, abroad, 84
product_d, 27, domestic, 25
product_d, 27, abroad, 2
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
Best Answer
Something like can do the work: