2012-03-18 75 views
2

以下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]; 
} 
+0

分裂($ 7, “ - ”); #正在工作,但03月因为我使用[2] = int(a [2])而转换为3;我如何转换为文本?这a [2] = var(a [2]);不起作用。 – shantanuo 2012-03-18 11:17:21

回答

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 
+0

正确。感谢你及时的答复。 – shantanuo 2012-03-18 11:23:39

+0

我只需要日期部分。 20120318足够了〜22:05:00没有必要。 – shantanuo 2012-03-18 11:45:41

相关问题