2

I have two CSV files and i have the requirement to calculate the sum of the 8th column from File1 and File2 for every row. The two CSV files have exactly 24 rows each and to simplify the things i have extracted the 8th row of each CSV file using:

awk -F, '{ print $8 }' >> FILE1
awk -F, '{ print $8 }' >> FILE2

Now, i have 2 file data in the following format:

File1

1
2
3
4

File2

2
3
4
5

How can i make the calculations in the way that

File1.Col1 + File2.Col1 = File3.Col1
File1.Col2 + File2.Col2 = File3.Col2
File1.Col3 + File2.Col3 = File3.Col3
.
.
.

resulting in:

File3

3
5
7
9

and so on using Bash Shell script because rest of my processing is being done in the same.

  • Don't you mean File1.Row1 + File2.Row1 = File3.Row1, etc? – PM 2Ring Aug 5 '15 at 12:13
  • 1
    I suggest doing all of your processing in an awk script; there's no need to extract the 8th columns of your CSV files into temporary files. To read two or more files in parallel you can use awk's getline statement. – PM 2Ring Aug 5 '15 at 12:17
  • Ankit: If the below answer has solved your issue please accept it & let the post be solved. It'll help others – neuron Aug 6 '15 at 18:24
3

paste File1 File2 | awk '{ print $1 + $2; }' > File3

  • Why do we need this ; in print statement? – Ankit Vashistha Aug 7 '15 at 5:31
  • Not required for a one liner, I had put some sanity check after that, forgot to remove it. – neuron Aug 7 '15 at 6:43
0

for avoiding an intermediate file, use:

paste <( awk -F, '{ print $8 }' original_file1 ) <( awk -F, '{ print $8 }' original_file2 ) | awk '{print $1+$2}' > file3
0

if both field are in 8th column among 24

 paste originalfile1 originalfile2 | awk '{print $8+$32 ; }' > file3 
  • 1
    It's 24 rows as per the OP :) – neuron Aug 5 '15 at 15:25
0

Using numsum and paste:

paste -d ' ' File[12] | numsum -r > File3

Or if DataFile1 and DataFile2 are the multi-column files from which File1 and File2 were extracted:

paste -d ' ' <(cut -f 8 DataFile1) <(cut -f 8 DataFile2) | numsum -r > File3

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.