Reputation: 1189
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?
Upvotes: 2
Views: 12850
Reputation: 204638
If you're just adding the fields you show then something like this is fine:
$ awk 'BEGIN{FS=OFS=","} {$3="NULL,"$3",NULL,NULL"; $0=$0",Tom"} 1' file
40,2012-05-30,NULL,London,NULL,NULL,61,Sunny,Tom
41,2012-02-22,NULL,Moscow,NULL,NULL,11,Snow,Tom
54,2012-04-10,NULL,Tokyo,NULL,NULL,02,Sunny,Tom
but if you're doing more than that then there's probably a better solution for that involving shifting fields and looping through the result populating empty fields with "NULL".
Upvotes: 0
Reputation: 85883
$ 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
Upvotes: 15
Reputation: 4887
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" }
Upvotes: 1