How to sum numbers in lines and create a single summary line

I have a file that is the result of running tests. Inside the file there are many 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 summed totals. In the above case, it would look like this:

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

I can awk them to create numbers in columns as follows:

$ 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 the columns and put them back in a row. Perhaps I am looking in the wrong direction. Any help appreciated

thank

AND

+4
source share
2 answers

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

For instance;

$ 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
+3

perl

perl -lne 'while(/(\d+) (\w+)/g){$x{$2}+=$1}}{print join(", ",map{"$_ $x{$_}"}keys %x)' f

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

Source: https://habr.com/ru/post/1660263/


All Articles