拆分字符串列"日期时间"进入" date" "时间"在CSV文件中

时间:2016-08-01 05:29:54

标签: csv unix awk

我有一个以下形式的csv文件:

$ head purchases.csv 
id,userID,itemID,price,platform,day
1,9132,id_005,3600,2,2014-10-30 17:29:46
2,67894,id_005,3000,1,2015-04-23 21:22:55
3,272780,id_004,1000,1,2014-11-27 16:58:30
4,302396,id_001,100,1,2014-12-11 08:35:07

现在,我想更改csv的最后一栏。目前,它在day形式的2014-10-30 17:29:46列中,即日期和时间之间有空格。但我想将此列拆分为两列daytime,以便在更改后csv文件变为:

$ head purchases.csv 
id,userID,itemID,price,platform,day,time
1,9132,id_005,3600,2,2014-10-30,17:29:46
2,67894,id_005,3000,1,2015-04-23,21:22:55
3,272780,id_004,1000,1,2014-11-27,16:58:30

如何从终端进行操作?

2 个答案:

答案 0 :(得分:2)

在$ 6上使用split

$ awk -v OFS=\, -F\, 'NR==1{print $0,"time";next} {split($6,a," "); print $1,$2,$3,$4,$5,a[1],a[2]}' test.in
id,userID,itemID,price,platform,day,time
1,9132,id_005,3600,2,2014-10-30,17:29:46
2,67894,id_005,3000,1,2015-04-23,21:22:55
3,272780,id_004,1000,1,2014-11-27,16:58:30
4,302396,id_001,100,1,2014-12-11,08:35:07

或者您可以使用gsub,只需用逗号代替空格:

$ awk -v OFS=\, -F\, 'NR==1{print $0,"time";next} {gsub(/ /,",",$6); print $0}' test.in

答案 1 :(得分:1)

James Brown's answer很有帮助,但是对列进行硬编码修改,同时还假设它是 last

一些简单的调整概括解决方案:

awk -v ndx=6 -F, 'NR==1 {sub(/$/, ",time", $ndx); print; next} sub(" ", ",", $ndx)' \
  purchases.csv