Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert columns into a CSV file using awk

Tags:

csv

sed

awk

I want to use sed to add some columns into the below csv file with default value.

My file is like:

40,2012-05-30,London,61,Sunny
41,2012-02-22,Moscow,11,Snow
54,2012-04-10,Tokyo,02,Sunny

I want the output to be:

40,2012-05-30,NULL,London,NULL,NULL,61,Sunny,Tom
41,2012-02-22,NULL,Moscow,NULL,NULL,11,Sunny,Tom
54,2012-04-10,NULL,Tokyo,NULL,NULL,02,Sunny,Tom

What are the best sed or awk commands to get the desired output?

like image 917
Xianlin Avatar asked Jan 16 '26 21:01

Xianlin


2 Answers

$ awk '{print $1,F,$2,F,F,$3,$4,$5,"Tom"}' FS=, OFS=, F='NULL' file
40,NULL,2012-05-30,NULL,NULL,London,61,Sunny,Tom
41,NULL,2012-02-22,NULL,NULL,Moscow,11,Snow,Tom
54,NULL,2012-04-10,NULL,NULL,Tokyo,02,Sunny,Tom
like image 85
Chris Seymour Avatar answered Jan 19 '26 20:01

Chris Seymour


This is a series of sed commands based on the examples here:

s/31,/31,NULL,/;
s/,01/NULL,NULL,01/;
s/.$/,Tom/

As for awk, maybe you could insert the fields first and update them later:

BEGIN { FS="," }
{ print $1","$2",NULL,"$3",NULL,NULL,"$4","$5",Tom" }
like image 45
icedwater Avatar answered Jan 19 '26 20:01

icedwater



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!