3

I am trying to manipulate a big data set, but I will use a simple example here. I am trying to add two columns to form a third column.

Input CSV

1,11  
2,12
3,13
4,14
5,15

Desired Output CSV

1,11,12
2,12,14
3,13,16
4,14,18
5,15,20

I have been trying the below line and I am getting the wrong output.

awk -F, '{$3=$1+$2;} {print $1,$2,$3}' OFS=, filename.csv
  • What output are you getting, exactly? – steeldriver Apr 27 '17 at 19:06
  • @steeldriver this is the output, ,121 ,142 ,163 ,184 ,205 – hmm1050 Apr 27 '17 at 19:11
  • Your code example works here – Thor Apr 27 '17 at 19:20
  • 2
    Is this a Windows file, perhaps? – terdon Apr 27 '17 at 19:22
  • @terdon i have used multiple csv file types and my results always come out jumbled together. I am just using small data sets but need this to work at scale. It works with just using a two column output but once I try to add the third I run into problems. – hmm1050 Apr 29 '17 at 0:52
3

Either of these:

awk -F, '{print $1","$2","$1+$2}' filename.csv
awk -F, '{$0=$1","$2","$1+$2}1' filename.csv

And for what it's worth, your example in the question worked fine for me. Locally and via awk.js.org tool.

$ awk -F, '{$3=$1+$2;} {print $1,$2,$3}' OFS=, filename.csv
1,11,12
2,12,14
3,13,16
4,14,18
5,15,20
$

works fine using online awk tool

  • 1
    whoa, awk REPL! nice – Neil McGuigan Apr 27 '17 at 19:47
  • @steve I am working from both the unix and linux cmd line, and my results keep getting jumbled like so, ,110 ,131 ,152 ,173 ,194 ,215 ,236 ,257 9,18,27 – hmm1050 Apr 29 '17 at 0:46
1
awk -F ',' '{$3=$1+$2;} {print $1","$2","$3}' filename.csv

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.