-1

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

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.

Thor
  • 42,211
  • 10
  • 116
  • 125
  • 1
    Have it like this way: `awk 'BEGIN{FS=OFS=","} {$3=$1+$2} 1' sum.csv > temp_file && mv temp_file sum.csv`. You need to either use `-i` inplace option of gawk OR use a temp file to have output in it and then save into actual Input_file, you are writing output into same Input_file. – RavinderSingh13 May 02 '22 at 10:07

1 Answers1

0

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.

Thor
  • 42,211
  • 10
  • 116
  • 125
Wiktor Stribiżew
  • 561,645
  • 34
  • 376
  • 476