Home > Software engineering >  awk to save changes in csv
awk to save changes in csv

Time:12-22

I wrote the following code:

BEGIN{FS=OFS=","}
     NR==FNR && 
     $7{sum =$7; 
     elementos  ; 
     next}
     !$7{$7=media}
     {print}
     ENDFILE{media=sum/elementos}

This awk script adds the average age to the empty cells on column 'age'.

Execution of the code is done as follows:

awk -f c_awk.awk train3.csv

Now I am trying to save the changes done in a new CSV file using awk. (new file: train4.csv)

I have been trying with > ./c_awk.awk/train4.csv in the last line but it doesn't work.

awk: c_awk.awk:12:      ENDFILE{media=sum/elementos}> /tmp/train4.csv
awk: c_awk.awk:12:                                  ^ syntax error
awk: c_awk.awk:12:      ENDFILE{media=sum/elementos}> /tmp/train4.csv
awk: c_awk.awk:12:                                               ^ syntax error

The file from where I am trying to implement the changes looks like this:

PassengerId,Survived,Pclass,Name,Sex,Age,SibSp,Parch,Ticket,Fare,Cabin,Embarked
1,0,3,"Braund, Mr. Owen Harris",male,22,1,0,A/5 21171,7.25,,S
2,1,1,"Cumings, Mrs. John Bradley (Florence Briggs Thayer)",female,38,1,0,PC 17599,71.2833,C85,C
3,1,3,"Heikkinen, Miss. Laina",female,26,0,0,STON/O2. 3101282,7.925,,S
4,1,1,"Futrelle, Mrs. Jacques Heath (Lily May Peel)",female,35,1,0,113803,53.1,C123,S
5,0,3,"Allen, Mr. William Henry",male,35,0,0,373450,8.05,,S
6,0,3,"Moran, Mr. James",male,,0,0,330877,8.4583,,Q
7,0,1,"McCarthy, Mr. Timothy J",male,54,0,0,17463,51.8625,E46,S

The expected result is the following:

1,0,3,"Braund, Mr. Owen Harris",male,22,1,0,A/5 21171,7.25,,S
2,1,1,"Cumings, Mrs. John Bradley (Florence Briggs Thayer)",female,38,1,0,PC 17599,71.2833,C85,C
3,1,3,"Heikkinen, Miss. Laina",female,26,0,0,STON/O2. 3101282,7.925,,S
4,1,1,"Futrelle, Mrs. Jacques Heath (Lily May Peel)",female,35,1,0,113803,53.1,C123,S
5,0,3,"Allen, Mr. William Henry",male,35,0,0,373450,8.05,,S
6,0,3,"Moran, Mr. James",male,,0,0,330877,8.4583,,Q
7,0,1,"McCarthy, Mr. Timothy J",male,54,0,0,17463,51.8625,E46,S

Thanks.

CodePudding user response:

awk -f c_awk.awk train3.csv > /tmp/train4.csv

or just change {print} to {print > "/tmp/train4.csv"}

Your script contains several issues unrelated to writing to a new file that I suspect you aren't aware of - you should post a new question with concise, testable sample input and expected output so we can help you with that as it's not entirely clear what you want that script to do

  • Related