amadain amadain - 1 month ago 17
Bash Question

How to sum up the numbers in strings and produce a single summary string

I have a file that is the result of running tests. Within the file there contains a lot of lines with the results of each test:

$ grep "tests," results/RunAll_unit_staging-dc1.txt
1 tests, 2 assertions, 0 failures, 0 errors, 0 skips
1 tests, 7 assertions, 0 failures, 0 errors, 0 skips
1 tests, 2 assertions, 1 failures, 0 errors, 0 skips
1 tests, 3 assertions, 0 failures, 0 errors, 0 skips
1 tests, 3 assertions, 0 failures, 0 errors, 0 skips
1 tests, 3 assertions, 0 failures, 0 errors, 0 skips
1 tests, 4 assertions, 0 failures, 0 errors, 0 skips
1 tests, 6 assertions, 0 failures, 0 errors, 0 skips
1 tests, 3 assertions, 0 failures, 0 errors, 0 skips
1 tests, 16 assertions, 0 failures, 0 errors, 0 skips
1 tests, 3 assertions, 0 failures, 0 errors, 0 skips
1 tests, 3 assertions, 0 failures, 0 errors, 0 skips
1 tests, 3 assertions, 0 failures, 0 errors, 0 skips
8 tests, 152 assertions, 0 failures, 0 errors, 0 skips
1 tests, 3 assertions, 0 failures, 0 errors, 0 skips
$


I was wondering if there is a way to combine these lines into a single summary line with the totals summed up. In the above case it would look like:

22 tests, 213 assertions, 1 failures, 0 errors, 0 skips


I can awk them to produce the numbers in columns like so:

$ grep "tests," results/RunAll_unit_staging-dc1.txt | awk '{print $1, $3, $5, $7, $9}'
1 2 0 0 0
1 7 0 0 0
1 2 1 0 0
1 3 0 0 0
1 3 0 0 0
1 3 0 0 0
1 4 0 0 0
1 6 0 0 0
1 3 0 0 0
1 16 0 0 0
1 3 0 0 0
1 3 0 0 0
1 3 0 0 0
8 152 0 0 0
1 3 0 0 0
$


but I'm not sure where to go from here to sum up the columns and place them back in the string. Maybe I'm looking in the wrong direction. Any help appreciated

Thx

A

Answer

you can try this;

awk '/tests/ {sum1+=$1; sum2+=$3;sum3+=$5; sum4+=$7;sum5+=$9;} END {printf "%d tests, %d assertions, %d failures, %d errors,%d skips\n" , sum1 ,sum2,sum3,sum4,sum5}' results/RunAll_unit_staging-dc1.txt

Eg;

$ awk '/tests,/ {sum1+=$1; sum2+=$3;sum3+=$5; sum4+=$7;sum5+=$9;} END {printf "%d tests, %d assertions, %d failures, %d errors, %d skips\n" , sum1 ,sum2,sum3,sum4,sum5}' testFile
22 tests, 213 assertions, 1 failures, 0 errors, 0 skips