我正在尝试将一列附加到包含 13 列的 csv 文件中。
我正在执行以下命令:
awk -F "," 'BEGIN{ OFS="," } {gsub(/"/, "", $1);$14=system("date -jf \"%m/%d/%Y %H:%M:%S %p\" \""$1"\" \"+%s\"");print}' mycsv.csv > test
结果是在 13 字段的末尾附加了以下内容^M,1
(或者^M,0
将新列的值(应该是 $14)添加到第二行。
因此 csv 中断。
这里有什么问题?
输入示例:
"1/30/2017 11:14:55 AM","I","M","k6.0.1","E","jim","JimK","JIM","[email protected]","A","6.0.12","A","Now"
预期输出:
"1/30/2017 11:14:55 AM","I","M","k6.0.1","E","jim","JimK","JIM","[email protected]","A","6.0.12","A","Now", 1485771295
更新:
这:
awk -F"," 'BEGIN{ OFS="," } {gsub(/"/, "", $1);system("date -jf \"%m/%d/%Y %H:%M:%S %p\" \""$1"\" \"+%s\"")|getline $14; print}' mycsv.csv > test
退出状态中没有 0 或 1,system
但具有^M
和 新行特征,因此 $14 打印在新行中
更新2:
$ cat mycsv.csv
"1/30/2017 11:14:55 AM","I","M","k6.0.1","E","jim","JimK","JIM","[email protected]","A","6.0.12","A","Now"
"1/30/2017 11:14:55 AM","I","M","k6.0.1","E","jim","JimK","JIM","[email protected]","A","6.0.12","A","Now"
"1/30/2017 11:14:55 AM","I","M","k6.0.1","E","jim","JimK","JIM","[email protected]","A","6.0.12","A","Now"
正在做:
$ awk -F"," '{printf; printf ","; gsub(/"/, "", $1);system("date -jf \"%m/%d/%Y %H:%M:%S %p\" \""$1"\" \"+%s\"")}' mycsv.csv > test
Failed conversion of ``1/30/2017 11:14:55 AM'' using format ``%m/%d/%Y %H:%M:%S %p''
date: illegal time format
usage: date [-jnu] [-d dst] [-r seconds] [-t west] [-v[+|-]val[ymwdHMS]] ...
[-f fmt date | [[[mm]dd]HH]MM[[cc]yy][.ss]] [+format]
结果文件:
当我做 cat 时,我看到:
$ cat test
,1485771295 11:14:55 AM","I","M","k6.0.1","E","jim","JimK","JIM","[email protected]","A","6.0.12","A","Now"
,148577129511:14:55 AM","I","M","k6.0.1","E","jim","JimK","JIM","[email protected]","A","6.0.12","A","Now"
当我用 vim 打开时,我看到一个^M
after"Now"
更新3:
奇怪的是,我无法打印整行。以下给出了垃圾:
$awk -F',' '{ printf $0 }' mycsv.csv
","M","k6.0.1","E","jim","JimK","JIM","[email protected]","A","6.0.12","A","Now""
但这是有效的(但我不想要打印添加的新行):
$ awk -F',' '{ print $0; }' mycsv.csv
"1/30/2017 11:14:55 AM","I","M","k6.0.1","E","jim","JimK","JIM","[email protected]","A","6.0.12","A","Now"
"1/30/2017 11:14:55 AM","I","M","k6.0.1","E","jim","JimK","JIM","[email protected]","A","6.0.12","A","Now"
"1/30/2017 11:14:55 AM","I","M","k6.0.1","E","jim","JimK","JIM","[email protected]","A","6.0.12","A","Now"
答案1
从awk(1)
我们读到的
system(cmd)
executes cmd and returns its exit status
所以0是系统命令结果返回的退出状态(正常退出)。在这种情况下,您可能需要打印现有的列、逗号,然后执行日期,以便将标准输出放在正确的位置,如简化示例所示:
(echo a,b,c; echo e,f,g) \
| awk -F, '{printf "%s", $0;printf ",";system("echo more")}'
使用第一列的输入附加新列并没有太大不同:打印数据,附加逗号,$1
为后续系统进行更改,进行系统调用。
$ cat input
"1/30/2017 11:14:55 AM","I","M"
$ awk -F, '{printf "%s", $0;printf ",";gsub(/"/, "", $1);system("date -jf \"%m/%d/%Y %H:%M:%S %p\" \""$1"\" \"+%s\"")}' input
"1/30/2017 11:14:55 AM","I","M",1485774895