Deepak
Deepak

Reputation: 414

how to add each element of a row from two files in linux

I want to write shell script which function as below description

  1. Cat file1 and file2 which have x number of rows and column(Equal number of rows and column). Both files where created already.
  2. Script should add(sum value of each element) each row's column element from file1 and file2 and generate output as file3. file1-: 10,10,10,10 11,11,11,11 file2-: 5,5,5,5 11,11,11 file3 would have output-: 15,15,15,15 22,22,22,22

Upvotes: 3

Views: 1028

Answers (2)

mockinterface
mockinterface

Reputation: 14860

Since you seem to know x, the number of columns, you can simply sum up explicitly. For example, with x=4:

--- script.sh ---
#!/bin/bash    
while true; do
  read -r c1 c2 c3 c4 <&3
  read -r d1 d2 d3 d4 <&4
  if [ -z "$c1" -o -z "$d1" ]; then
    break
  fi
  echo "$(($c1 + $d1)) $(($c2 + $d2)) $(($c3 + $d3)) $(($c4 + $d4))" >>3.txt
done 3<1.txt 4<2.txt

Here's a sample run:

$ ./script.sh && cat 1.txt 2.txt 3.txt
1 2 3 4
5 6 7 8
9 9 9 9

1 1 1 1
1 1 1 1
1 1 1 1

2 3 4 5
6 7 8 9
10 10 10 10

Upvotes: 3

shx2
shx2

Reputation: 64288

I know you asked for a shell script, but I find this kind of task very easy to achieve using python.

So in case it helps anyone, here's a quick python script. This script supports an arbitrary number of input files (one or more):

#! python
import sys
if len(sys.argv) <= 1:
    raise RuntimeError('usage: %s file1 file2' % sys.argv[0])
for lines in zip(sys.args[1:]):
   print sum( float(line.strip()) for line in lines )

Upvotes: 0

Related Questions