Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

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

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

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. – A-D Jan 4, 2017 at 23:23 @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. – Michelle Tan Jan 4, 2017 at 23:27
$ 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
  • awk -v OFS=", " -v d=$mydate '$0 = $0 OFS ( NR==1?"date":d )' (seems the d of assignation is missing – NeronLeVelu Jan 5, 2017 at 8:12 @NeronLeVelu Yeah it was. I wrote it before 7AM, I'm amazed if it was the only thing missing... – James Brown Jan 5, 2017 at 8:52 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 – NeronLeVelu Jan 5, 2017 at 9:58

    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

    Thanks for contributing an answer to Stack Overflow!

    • Please be sure to answer the question. Provide details and share your research!

    But avoid

    • Asking for help, clarification, or responding to other answers.
    • Making statements based on opinion; back them up with references or personal experience.

    To learn more, see our tips on writing great answers.