Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to sum two columns and save the values to third column using Linux shell command

I have a sum.csv file I want to sum column 1 contents and column 2 contents and save the results to column 3, let say input is

1,2
3,4
5,6

Required output is

1,2,3
3,4,7
5,6,11

I am using the command awk

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

awk -F "," '{$3=$1+$2}{print $3}'>>"sum.csv" sum.csv

It will create output in my sum.csv file as

1,2
3,4
5,6
3
7
11

But I want:

1,2,3
3,4,7
5,6,11

How can I get the output please guide me, also it should save on same file.

>Solution :

You can use

awk -F, '{print $0 OFS $1+$2}' OFS=, file > newfile
awk 'BEGIN{FS=OFS=","} {print $0 OFS $1+$2}' file > newfile
awk -F, '$0=$0FS$1+$2' file > newfile

See an online demo.

With -F,/OFS=, (or BEGIN{FS=OFS=","}) you set the input and output field separator to a comma, and with print $0 OFS $1+$2 you output the line plus the comma and the sum of the two filed values.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading