2

I have a csv with the following format

header1,header2,header3 data1, data2, data3 data4, data5, data6 

I want to add a date column that will make the csv look like this

header1,header2,header3, date data1, data2, data3, 01/04/2017 data4, data5, data6, 01/04/2017 

I tried the following awk command but it adds date in the header row as well. I am newbie with awk and do not know how to get that working

mydate=$(date) awk -v d="$mydate" -F"," 'BEGIN { OFS = "," } {$4=d; print}' input.csv > output.csv 

3 Answers 3

1

Are you looking for something like this?

awk -v date="4/1/17" -F"," 'BEGIN { OFS = "," } NR==1 {print $0 " ,date"} NR>1 {$4=date; print}' 

NR refers to number of record. like line number. These in-built variables might be useful for you: http://www.thegeekstuff.com/2010/01/8-powerful-awk-built-in-variables-fs-ofs-rs-ors-nr-nf-filename-fnr/?ref=binfind.com/web

Sign up to request clarification or add additional context in comments.

2 Comments

I just tried your solution, its pretty close to what i am looking for but instead of adding a new column at the last, it is appending the date to the 2nd last column in the csv.
@AshutoshD Just add a new column with the date variable instead. like what you did. awk -v date="4/1/17" -F"," 'BEGIN { OFS = "," } NR==1 {print $0 " ,date"} NR>1 {$4=date; print}' . It should work then.
1

Another in awk using conditional operator:

$ mydate="5/1/2017" $ awk -v OFS=", " -v d=$mydate '$0 = $0 OFS ( NR==1?"date":d )' file header1,header2,header3, date data1, data2, data3, 5/1/2017 data4, data5, data6, 5/1/2017 
  • OFS=", ", FS may remain default as it is not needed
  • date goes in d var
  • implicit print
  • conditional operator to print either date on the first record or d on all others

3 Comments

awk -v OFS=", " -v d=$mydate '$0 = $0 OFS ( NR==1?"date":d )' (seems the d of assignation is missing
@NeronLeVelu Yeah it was. I wrote it before 7AM, I'm amazed if it was the only thing missing...
i discover that content ($0 here) could be changed in "pattern" condition part of the script AND directly used as resulting (line in this case) with your script
0

sed version is a alternative in this case

mydate="6/1/2017";sed -e '1 s/$/,date/;b' -e "s/\$/,${mydate}/" YourFile 

sed allow an inline edition (no explicit intermediate file) with option -i that is sometime usefull

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.