仅提取日期和时间的日期

时间:2012-03-18 10:31:34

标签: awk

以下awk代码按预期工作。

像2012-03-10~12:59:41这样的日期四舍五入到最近的五分钟,例如2012-03-10〜12:55:00

如何更改它以便我可以获得像20120310一样的年月日(没有破折号)?

BEGIN {
    # all fields are separated by ^
    FS = "^";
}
{
    # $7 is the date and time in the form yyyy-mm-dd hh:mm:ss.
    # Split at colons to get hours minutes and seconds into a[1]
    # through a[3].  Round minutes to nearest 5.
    split($7, a, ":");
    a[2] = int(a[2] / 5) * 5;
    # print first, second and forth field, then rounded time.
    printf "set %s:%s:%s %s:%02d:00\\r\\n\n", $1, $2, $4, a[1], a[2];
}

1 个答案:

答案 0 :(得分:2)

更改分割线以使用gensub()

$ cat file 
1^2^3^4^5^6^2012-03-18~22:09:10

awk 'BEGIN {
         # all fields are separated by ^
         FS = "^";
     }
     {
         # $7 is the date and time in the form yyyy-mm-dd hh:mm:ss.
         # Split at colons to get hours minutes and seconds into a[1]
         # through a[3].  Round minutes to nearest 5.
         split(gensub(/-/,"","g",$7),a,":")
         a[2] = int(a[2] / 5) * 5;
         # print first, second and fourth field, then rounded time.
         printf "set %s:%s:%s %s:%02d:00\\r\\n\n", $1, $2, $4, a[1], a[2];
     }' file

输出:

set 1:2:4 20120318~22:05:00\r\n