2

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?

1
  • One single sed command is probably not going to be enough to add all those fields to your CSV. Commented Oct 7, 2013 at 8:53

3 Answers 3

15
$ 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
Sign up to request clarification or add additional context in comments.

1 Comment

Like that it looks like magic... What are FS and OFS?
1

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" }

Comments

0

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".

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.