Lucas
Lucas

Reputation: 47

How to add a column in a csv file (at middle and end) in bash linux using awk?

The input.csv is:

id, name, shortName
1, Example1, Ex1
2, Example2, Ex2

I need to add a column of date. So the output.csv should be:

id, 2021-06-23, name, shortName
1,  2021-06-23, Example1, Ex1
2,  2021-06-23, Example2, Ex2.

For this purpose, i used this comand:

awk -F"," 'BEGIN { FS=OFS = "," } {$2="2021-06-23"; print}' input.csv 

But, when i did it the column "name" was deleted. The output was like this:

id, 2021-06-23, shortName
1,  2021-06-23, Ex1
2,  2021-06-23, Ex2.

Then, i also tried put the colum at the end with the comand:

awk -F"," 'BEGIN { FS=OFS = "," } {$4="2021-06-23"; print}' input.csv 

But the exit was even stranger:

,  2021-06-23 
,  2021-06-23
,  2021-06-23

So, I would like to know what I'm doing wrong both in the case of adding a column to the middle of the csv file and adding it to the end.

Obs.: I am now learning how to use it and therefore I believe that my mistakes must be a beginner's mistakes.

Upvotes: 2

Views: 1865

Answers (1)

Daweo
Daweo

Reputation: 36370

This

awk -F"," 'BEGIN { FS=OFS = "," } {$2="2021-06-23"; print}' input.csv

does overwrite 2nd column using 2021-06-23. Note also that this code is redundant - you are setting field seperator twice, once using -F then setting FS in BEGIN, code above has same effect as

awk 'BEGIN { FS=OFS = "," } {$2="2021-06-23"; print}' input.csv

You want to add column, if you know in advance number of columns in your .csv file you might do, for 3 columns:

awk 'BEGIN{FS=OFS=", "}{print $1,"2021-06-23",$2,$3}' input.csv

which for input.csv content being

id, name, shortName
1, Example1, Ex1
2, Example2, Ex2

output

id, 2021-06-23, name, shortName
1, 2021-06-23, Example1, Ex1
2, 2021-06-23, Example2, Ex2

(tested in gawk 4.2.1)

Upvotes: 2

Related Questions