Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum number in two different files

Tags:

bash

shell

awk

I have two files of same lenght like:

0.99952 0.01
0.98927 0.02
0.98242 0.03

and

-0.758 0.01
-0.745 0.02
-0.742 0.03

I would like to sum the first column numbers and print it in a new file with the same elements alongside in the second column. The output should be:

0.24152 0.01
0,24427 0.02
0,24042 0.03

I tried with

 paste file1 file2 | awk '{print ($1 + $2), $4}' > sum

but the output is:

 1.00952 0.01
 1.00927 0.02
 1.01242 0.03
like image 776
Valerio D. Ciotti Avatar asked Apr 13 '13 09:04

Valerio D. Ciotti


2 Answers

You taking invalid parameter number in awk ($2 instead of $3)

$1      $2      $3     $4
0.99952 0.01    -0.758 0.01
0.98927 0.02    -0.745 0.02
0.98242 0.03    -0.742 0.03

There is a working example:

paste data1 data2 | awk '{print ($1 + $3), $4}'
like image 138
loentar Avatar answered Oct 27 '22 00:10

loentar


The single awk approach:

$ awk 'NR==FNR{a[NR]=$1;next}{print $1+a[FNR],$2}' file1 file2
0.24152 0.01
0.24427 0.02
0.24042 0.03
like image 36
Chris Seymour Avatar answered Oct 27 '22 00:10

Chris Seymour