如何使用bash脚本中的awk过滤2个日期之间的数据 [英] How to filter data between 2 dates with awk in a bash script

查看:594
本文介绍了如何使用bash脚本中的awk过滤2个日期之间的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

  ####< 2015年1月19日07:16 :47点UTC> <注意事项> < Stdout> < example.com> 
####< 2015年1月20日07:16:43 UTC> <注意事项> < Stdout> < example2.com>
####< 2015年1月21日07:16:48 UTC> <注意事项> < Stdout> < example3.com>

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



我尝试使用 awk 但是, code> 2015年1月19日至 2015-01-19 继续比较日期。

解决方案

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

 #!/ usr / bin / awk -f 

#将时间戳格式化为一个数字,所以更高的数字代表
#a以后的时间戳。这不会处理时区,因为日期
#不能处理时钟符号。我希望所有的时间戳都使用
#相同的时区,否则你将不得不在这里加入支持。
函数datefmt(d){
#使d与单引号的shell字符串兼容
gsub(/'/,'\\'',d)

#然后运行date命令并获取其输出
command =date -dd'+%Y%m%d%H%M%S
command | getline result
close(command)

#这是我们的结果。
返回结果;
}

BEGIN {
#字段分隔符,所以我们要解析的时间戳的部分是$ 2和$ 3
FS =[<> ] +

#start,end set here。
start = datefmt(2015年1月19日00:00:00)
end = datefmt(2015年1月20日23:59:59)
}

{
#将时间戳转换成一个容易比较的格式
stamp = datefmt($ 2$ 3)

#然后只打印时间戳的行在范围内。
if(stamp> = start&&&& stamp< = end){
print
}
}
pre>

Hi I have the following log file structure:

####<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>

How can I filter this file by a date interval, for example: Show all data between 19'th and 20'th of January 2015

I tried to use awk but I have problems converting 19-Jan-2015 to 2015-01-19 to continue comparison of dates.

解决方案

For an oddball date format like that, I'd outsource the date parsing to the date utility.

#!/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
  }
}

这篇关于如何使用bash脚本中的awk过滤2个日期之间的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆