2

I want to add numbers from two txt files. The number will change in file1, and file2 should update itself like this file2 = file1 + file2. Decimals not needed.

Example:

file1

3 

file2

7 

Output:

file1

3 

file2

10 

I tried $ paste file1 file2 | awk '{$0 = $1 + $2}' > file2 but all it does is copy the number from file1 to file2.

3 Answers 3

5

In-place replacements are not natively supported in awk. You can use sponge from moreutils to rewrite to a file you read in.

awk-way to add two files line-by-line

awk ' FNR==NR { a[NR]=$1 } FNR!=NR { print $1+a[FNR] }' file1 file2 | sponge file2 

Simpler non-awk way, that also supports floating points:

paste -d'+' file1 file2 | bc -l | sponge file2 

Both methods support multi-line files.

2

You could do this:

let tot=$(cat file1)+$(cat file2) echo $tot 
0

I have tried with command and it worked fine too

paste f1 f2| awk '{print $1+$2}' >f2_tmp && mv f2_tmp f2 praveen@praveen:~$ cat f1 3 praveen@praveen:~$ cat f2 10 praveen@praveen:~$ 

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.