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
–
–
$ 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
–
–
–
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.