这是gawk 4.0.0,在带有cygwin的Windows 7上运行。该程序被调用,如
gawk -f procjournal.gawk testdata
我有一些看起来像这样的数据:
"Date";"Type";"Amount";"Balance"
"6/11/2013 11:51:17 AM";"Transaction Tax";-427.5;399313884.46
"6/11/2013 11:51:17 AM";"Market Transaction";47500;399314311.96
"6/11/2013 11:12:42 AM";"Transaction Tax";-549.92;399266811.96
"6/11/2013 11:12:42 AM";"Market Transaction";61101.78;399267361.88
我想提取事务的行,从第1个字段中删除日期部分,然后将时间戳重新格式化为小数。我以为我可以用这个awk程序做到这一点:
FS=";"
OFS=";"
/Market Transaction/ {
split($1, itemdate, " ");
tmp = itemdate[2];
split(tmp, hms, ":");
timestamp = hms[3] + (hms[2] * 60) + (hms[1] * 3600);
if (itemdate[3] == "AM")
timestamp += 12 * 3600;
timestamp /= 3600.0;
$1 = timestamp;
print;
}
但我的输出如下:
"Date";"Type";"Amount";"Balance"
"Date";"Type";"Amount";"Balance"
"6/11/2013 11:51:17 AM";"Transaction Tax";-427.5;399313884.46
"6/11/2013 11:51:17 AM";"Transaction Tax";-427.5;399313884.46
"6/11/2013 11:51:17 AM";"Market Transaction";47500;399314311.96
"6/11/2013 11:51:17 AM";"Market Transaction";47500;399314311.96
11.8547;"Market Transaction";47500;399314311.96
"6/11/2013 11:12:42 AM";"Transaction Tax";-549.92;399266811.96
"6/11/2013 11:12:42 AM";"Transaction Tax";-549.92;399266811.96
"6/11/2013 11:12:42 AM";"Market Transaction";61101.78;399267361.88
"6/11/2013 11:12:42 AM";"Market Transaction";61101.78;399267361.88
11.2117;"Market Transaction";61101.78;399267361.88
为什么要打印不匹配的行,我该如何抑制它?
答案 0 :(得分:6)
更改脚本以在BEGIN
块中包含分隔符。
脚本内容:
BEGIN {
FS=";"
OFS=";"
}
/Market Transaction/ {
split($1, itemdate, " ");
tmp = itemdate[2];
split(tmp, hms, ":");
timestamp = hms[3] + (hms[2] * 60) + (hms[1] * 3600);
if (itemdate[3] == "AM")
timestamp += 12 * 3600;
timestamp /= 3600.0;
$1 = timestamp;
print;
}
答案 1 :(得分:0)
不是您问题的答案,而是计算时间的另一种方式:
if (match($1, /([0-9]?[0-9]):([0-9][0-9]):([0-9][0-9]) ([AP]M)/, a)) {
$1 = a[1] + (a[2]*60 + a[3])/3600 + (a[4] == "PM" ? 12 : 0)
}