在BASH脚本中使用"awk"将列添加到CSV文件的末尾 [英] Add Column to end of CSV file using 'awk' in BASH script

查看:48
本文介绍了在BASH脚本中使用"awk"将列添加到CSV文件的末尾的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用变量中的字符串将列添加到CSV文件的末尾?

How do you add a column to the end of a CSV file with using a string in a variable?

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 中的上述尝试将字符串添加到末尾,但去除了所有逗号分隔符.

My attempt above in awk.sh added the string to the end but stripped all the comma separators.

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

感谢任何帮助!

#!/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 -v d="$TIMESTAMP" -F"," 'BEGIN {OFS = ","} {$6=d; print}' $ORIG_FILE > $NEW_FILE
rm -f $ORIG_FILE

推荐答案

您可以在 OFS (输出字段分隔符)中添加逗号:

You may add a comma to OFS (Output Field Separator):

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 中使用它:

So assign your date to a shell variable and use it inside awk:

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

这篇关于在BASH脚本中使用"awk"将列添加到CSV文件的末尾的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆