【问题标题】:Is there a way to filter a log file based on the date read as argument?有没有办法根据作为参数读取的日期过滤日志文件?
【发布时间】:2021-06-18 13:44:23
【问题描述】:

我正在处理这个日志文件:

2021-03-21 20:06:45; ABC; 531.54
2021-03-21 20:06:47; DEF; 136. 81
2021-03-21 20:06:51; GHI; 222.34

我想知道是否可以使用 awk 为文件创建过滤器,以便在应用它后打印出的唯一行是日期晚于作为参数提供给脚本的日期的行。 我将脚本运行为:

./script -a 2021-03-21 20:06:46

并且期望输出是:

2021-03-21 20:06:47; DEF; 136. 81
2021-03-21 20:06:51; GHI; 222.34

如何做到这一点?

【问题讨论】:

  • awk 不会成为这项任务的好工具,因为它对过滤日期一无所知。几乎所有更高级别的语言(python/ruby/php/perl/etc)都具有用于解析日期的内置功能,这将使这项任务变得更加容易。

标签: shell date awk filter


【解决方案1】:

如果支持mktime()功能的GNU Awk可用,请尝试以下方法:

#!/bin/bash

dy=$1   # e.g. "2021-03-21"
tm=$2   # e.g. "20:06:46"

awk -F ";" -v dy="$dy" -v tm="$tm" '            # pass bash arguments to awk
    BEGIN { gsub("-", " ", dy); gsub(":", " ", tm); given = mktime(dy " " tm) }
                                                # convert the passed day&time to the seconds since the epoch
    {
        str = $1; gsub("[-:]", " ", str)        # extract the timestamp out of the log line
        sec = mktime(str)                       # convert it to the seconds since the epoch
        if (sec > given) print                  # compare with the given day&time
    }
' file.log

将上面的脚本另存为文件,例如script,使用chmod a+x script 添加可执行权限,然后使用./script 2021-03-21 20:06:46 之类的内容调用。
输出将是:

2021-03-21 20:06:47; DEF; 136. 81
2021-03-21 20:06:51; GHI; 222.34

[替代方案]
即使没有mktime() 函数,你也可以说:

awk -F ";" -v dy="$1" -v tm="$2" '
    $1 > dy " " tm
' file.log

这将输出相同的结果。这是可行的,因为给定的日期和时间字符串可以按字典顺序进行比较。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-08
    • 2011-12-04
    • 2016-11-09
    • 2021-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-06
    相关资源
    最近更新 更多