linux - 如何在 bash 脚本中使用 awk 过滤 2 个日期之间的数据

标签 linux bash date awk gnu

<分区>

您好,我有以下日志文​​件结构:

####<19-Jan-2015 07:16:47 o'clock UTC> <Notice> <Stdout> <example.com>
####<20-Jan-2015 07:16:43 o'clock UTC> <Notice> <Stdout> <example2.com>
####<21-Jan-2015 07:16:48 o'clock UTC> <Notice> <Stdout> <example3.com>

如何按日期间隔过滤此文件,例如: 显示2015年1月19日到20日的所有数据

我尝试使用 awk 但我在将 19-Jan-2015 转换为 2015-01-19 以继续比较日期时遇到问题.

最佳答案

对于像这样的古怪日期格式,我会将日期解析外包给 date 实用程序。

#!/usr/bin/awk -f

# Formats the timestamp as a number, so that higher numbers represent
# a later timestamp. This will not handle the time zone because date
# can't handle the o'clock notation. I hope all your timestamps use the
# same time zone, otherwise you'll have to hack support for it in here.
function datefmt(d) {
  # make d compatible with singly-quoted shell strings
  gsub(/'/, "'\\''", d)

  # then run the date command and get its output
  command = "date -d '" d "' +%Y%m%d%H%M%S"
  command | getline result
  close(command)

  # that's our result.
  return result;
}

BEGIN {
  # Field separator, so the part of the timestamp we'll parse is in $2 and $3
  FS = "[< >]+"

  # start, end set here.
  start = datefmt("19-Jan-2015 00:00:00")
  end   = datefmt("20-Jan-2015 23:59:59")
}

{
  # convert the timestamp into an easily comparable format
  stamp = datefmt($2 " " $3)

  # then print only lines in which the time stamp is in the range.
  if(stamp >= start && stamp <= end) {
    print
  }
}

关于linux - 如何在 bash 脚本中使用 awk 过滤 2 个日期之间的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28275880/

相关文章:

python - 如何在 python 中使用星期几和月份日期来获取年份?

c++ - QX11EmbedContainer 和 QProcess 问题

php - UTF-8贯穿始终

bash - 为什么我不能用expect脚本来启动redis?

BASH Loop 怎么走呢?

r - R中的格式日期(年-月)

Linux环境,定时器回调与应用线程的同步

linux - NTP客户端无纪律本地时钟

json - 将 JSON 转换为 bash 环境变量

php - 如何使用 php 获取月份中的日期?