在BASH脚本中使用'awk'将列添加到CSV文件的末尾

如何使用variables中的string将一列添加到CSV文件的末尾?

input.csv

2012-02-29,01:00:00,Manhattan,New York,234 2012-02-29,01:00:00,Manhattan,New York,843 2012-02-29,01:00:00,Manhattan,New York,472 2012-02-29,01:00:00,Manhattan,New York,516 

output.csv

 2012-02-29,01:00:00,Manhattan,New York,234,2012-02-29 16:13:00 2012-02-29,01:00:00,Manhattan,New York,843,2012-02-29 16:13:00 2012-02-29,01:00:00,Manhattan,New York,472,2012-02-29 16:13:00 2012-02-29,01:00:00,Manhattan,New York,516,2012-02-29 16:13:00 

awk.sh

 #!/bin/bash awk -F"," '{$6="2012-02-29 16:13:00" OFS $6; print}' input.csv > output.csv 

我在awk.sh上面的尝试在最后添加了string,但删除了所有的逗号分隔符。

awk.sh结果

 2012-02-29 01:00:00 Manhattan New York 234 2012-02-29 16:13:00 2012-02-29 01:00:00 Manhattan New York 843 2012-02-29 16:13:00 2012-02-29 01:00:00 Manhattan New York 472 2012-02-29 16:13:00 2012-02-29 01:00:00 Manhattan New York 516 2012-02-29 16:13:00 

感谢任何帮助!

更新了awk.sh

 #!/bin/bash GAWK="/bin/gawk" TIMESTAMP=$(date +"%F %T") ORIG_FILE="input.csv" NEW_FILE="output.csv" #Append 'Create' DateTimeStamp to CSV for MySQL logging $GAWK -vd="$TIMESTAMP" -F"," 'BEGIN {OFS = ","} {$6=d; print}' $ORIG_FILE > $NEW_FILE rm -f $ORIG_FILE 

您可以向OFS (输出字段分隔符)添加一个逗号:

 awk -F"," 'BEGIN { OFS = "," } {$6="2012-02-29 16:13:00"; print}' input.csv > output.csv 

输出:

 2012-02-29,01:00:00,Manhatten,New York,234,2012-02-29 16:13:00 2012-02-29,01:00:00,Manhatten,New York,843,2012-02-29 16:13:00 2012-02-29,01:00:00,Manhatten,New York,472,2012-02-29 16:13:00 2012-02-29,01:00:00,Manhatten,New York,516,2012-02-29 16:13:00 

编辑回答SirOracle的评论:

awk手册页:

  -v var=val --assign var=val Assign the value val to the variable var, before execution of the program begins. Such variable values are available to the BEGIN block of an AWK program. 

所以把你的日期分配给一个shell变量,并在awk使用它:

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

我会做:

 awk '{ printf("%s,2012-02-29 16:13:00\n", $0); }' input.csv > output.csv 

这个硬编码的价值,但你的代码也是如此。

或者你可以使用sed

 sed 's/$/,2012-02-29 16:13:00/' input.csv > output.csv 

您可以设置OFS(输出字段分隔符):

 awk -F"," 'BEGIN { OFS = "," } ; {$6="2012-02-29 16:13:00" OFS $6; print}' input.csv >output.csv 

这给了我:

 2012-02-29,01:00:00,Manhatten,New York,234,2012-02-29 16:13:00, 2012-02-29,01:00:00,Manhatten,New York,843,2012-02-29 16:13:00, 2012-02-29,01:00:00,Manhatten,New York,472,2012-02-29 16:13:00, 2012-02-29,01:00:00,Manhatten,New York,516,2012-02-29 16:13:00,