【问题标题】:extract only date from date and time从日期和时间中仅提取日期
【发布时间】:2013-08-12 12:15:42
【问题描述】:

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

【问题讨论】:

  • split($7, a, "-"); # 正在工作,但是第 03 个月被转换为 3,因为我使用了 a[2] = int(a[2]);如何转换为文本?这 a[2] = var(a[2]);不起作用。

标签: awk


【解决方案1】:

将分割线更改为使用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

【讨论】:

  • 正确。感谢您的快速回答。
  • 我只需要日期部分。 20120318 就足够了~22:05:00 没必要。
猜你喜欢
  • 1970-01-01
  • 2017-04-05
  • 2014-11-20
  • 1970-01-01
  • 1970-01-01
  • 2016-02-23
  • 1970-01-01
  • 2019-01-23
  • 2015-10-30
相关资源
最近更新 更多