Reputation: 39
I have a csv and for each line in the csv, I need to add new columns. One of the columns is a timestamp and it seems to be breaking the operation.
Example:
col1,col2,col3
1,2,3
4,5,7
After
col1,col2,col3,col4,col5,col6
1,2,3,01-01-2020 01:01:01,name,class
4,5,7,01-01-2020 01:01:01,name,class
I used How to add new column with header to csv with awk for reference.
ORIG_FILE='sample.csv'
NEW_FILE='new_sample.csv'
values="01-01-2020 01:01:01,name,class"
awk -v d=$values -F"," 'BEGIN {OFS = ","} {printf("%s%s",$0,FNR>1?d RS:"col4,col5,col6" RS)}' $ORIG_FILE > $NEW_FILE
I am very new to using bash and I am trying to figure this out.
Any help greatly appreciated.
Upvotes: 3
Views: 339
Reputation: 204311
orig_file='sample.csv'
new_file='new_sample.csv'
values='01-01-2020 01:01:01,name,class'
awk -v d="$values" 'BEGIN{FS=OFS=","} { print $0, (NR>1 ? d : "col4,col5,col6") }' "$orig_file" > "$new_file"
Always quote your shell variables and don't use all upper case for non-exported shell variable names.
Upvotes: 4