3

I'm trying to add a column to a csv file by using:

awk -F "," '{print $0"new_col"}' file.csv

but I got :

new_col8,0.405,0.101
new_col4,0.374,0.100
new_col23,0.342,0.100
new_col130,0.298,0.100

instead of :

68,110,0.362,0.101,new_col
11,98,0.405,0.101,new_col
57,94,0.374,0.100,new_col
61,123,0.342,0.100,new_col
124,130,0.298,0.100,new_col

I tried like this too:

awk -F "," '{{$(NF+1)=",new_col"} print $0 }' file.csv

but i got the same result!!!

Is someone already had this problem?

1
  • awk -F , '{print $0 ",new_col"}' file.csv just works on me. Can you try it? And just awk '{print $0 ",new_col"}' file.csv seem to work too. Commented Aug 19, 2014 at 6:17

3 Answers 3

3

Your input csv file is in DOS format. Microsoft DOS/Windows use a Carriage Return (\r, ^M, ASCII code 13) followed by a Line Feed (\n, ^J or ASCII code 10) at the end of each line while Linux/Unix uses the Line feed only.

To fix this, run:

$ dos2unix file.csv
dos2unix: converting file file.csv to Unix format ... 
$ awk '{print $0",new_col"}' file.csv

Note the comma before new_col. Without it, print concatenates new_col directly onto the end of $0. There is no need to signify the field seperator (-F) because you are not splitting the input line into fields - you are only using $0.

0

If the .csv is in DOS format another option might be:

tr -d \\r <input.csv | sed 's/$/,new_col/'

...which would handle it all in one shot.

0
0

Would this work? awk -F, '{$(NF+1)="new_col";}1' OFS=, input.txt.

This will output the new table in command line. In the example, I've added an output file (output.csv just in case).

Before running the command:

$ cat input.csv
68,110,0.362,0.101
11,98,0.405,0.101
57,94,0.374,0.100
61,123,0.342,0.100
124,130,0.298,0.100

Executing the command:

$ awk -F, '{$(NF+1)="new_col";}1' OFS=, input.csv > output.csv

Checking output file:

$ cat output.csv
68,110,0.362,0.101,new_col
11,98,0.405,0.101,new_col
57,94,0.374,0.100,new_col
61,123,0.342,0.100,new_col
124,130,0.298,0.100,new_col

Example page

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.