sed匹配日期和奇数格式

问题描述 投票:0回答:1

我遇到了sed的问题,我试图根据日期进行匹配,以便我可以捕获特定日期/时间的所有日志并将其上传到API。然后我将最后一次运行日期存储为新的开始日期。

我遇到的问题是'开始'和'结束'日期不一定存在于文件中,我希望根据日期/时间尽可能接近匹配。我目前所拥有的代码似乎仅在源文件中存在两个日期时才起作用。

    function logs() {
        timestamplastupload="`cat /tmp/latest-timestamp.txt`"
        timestampnow=`date +"%a %b %_d %H:%M:%S %Y"`
        echo "$timestampnow" > /tmp/latest-timestamp.txt


        while read -r line; do
            curl -X POST -d "$line" https://logserver/api/NewLog --ntlm --user xx:xx       
        done < <(sed -rne '/'"$timestamplastupload"'/,/'"$timestampnow"'/ p' /var/log/fullaccess.log)
    }

有没有办法指定sed匹配做什么或以某种方式找到最接近的文件中的行,所以我可以确保我只上传新的日志行而没有在API端进行大量的比较工作与匹配每一个在那里的数据存储中输入。

这是我正在尝试解析的日志文件的示例:

Thu Mar  1 21:07:14 2018 us=56799   ifconfig_ipv6_pool_netbits = 0
Thu Mar  1 21:07:14 2018 us=56808   n_bcast_buf = 256
Thu Mar  1 21:07:14 2018 us=56817   tcp_queue_limit = 64
Thu Mar  1 21:07:14 2018 us=56826   real_hash_size = 256
Thu Mar  1 21:07:14 2018 us=56835   virtual_hash_size = 256
Wed Feb 28 22:10:48 2018 us=184134   ifconfig_nowarn = DISABLED
Wed Feb 28 22:10:48 2018 us=184143   ifconfig_ipv6_local = '[UNDEF]'
Wed Feb 28 22:10:48 2018 us=184152   ifconfig_ipv6_netbits = 0
Wed Feb 28 22:10:48 2018 us=184161   ifconfig_ipv6_remote = '[UNDEF]'

还要注意单个日期之前的填充空间,这也可能会在这里投入扳手。我以为通过提供+%_ d的日期来解决这个问题

提前致谢

regex bash sed scripting
1个回答
1
投票

尽管sed对于模式匹配很有用,但它可能不适合进行值比较。从这个意义上讲,AWK会更好。 时间比较的常用方法是将日期字符串转换为自纪元以来的秒数。但是将日期和时间合并为单个数字更为实际,例如,将“Feb 28 22:10:48 2018”转换为“20180228221048”。这是一个例子:

function logs() {
    timestamplastupload="`cat /tmp/latest-timestamp.txt`"
    timestampnow=`date +"%a %b %_d %H:%M:%S %Y"`
    echo "$timestampnow" > /tmp/latest-timestamp.txt

    while read -r line; do
        curl -X POST -d "$line" https://logserver/api/NewLog --ntlm --user xx:xx
    done < <(awk -v timestamplastupload="$timestamplastupload" -v timestampnow="$timestampnow" '
    # initialize variables
    BEGIN {
        monstr = "JanFebMarAprMayJunJulAugSepOctNovDec";
        for (i = 1; i <= 12; i++) {
            mon2mm[substr(monstr, i * 3 - 2, 3)] = i;
        }
        split(timestamplastupload, ary, " ");
        start = date2str(ary[2], ary[3], ary[4], ary[5]);
        split(timestampnow, ary, " ");
        end = date2str(ary[2], ary[3], ary[4], ary[5]);
    }
    # merge date and time into a scalar number
    function date2str(mon, day, time, year,
        hms, datestr) {
        split(time, hms, ":");
        datestr = sprintf("%04d%02d%02d%02d%02d%02d",
            year, mon2mm[mon], day, hms[1], hms[2], hms[3]);
        return datestr;
    }
    # main loop
    {
        logtime = date2str($2, $3, $4, $5);
        if (logtime >= start && logtime <= end) {
            print;
        }
    }
    ' /var/log/fullaccess.log)
}

对不起,这是一个漫长而不优雅的解决方案。

© www.soinside.com 2019 - 2024. All rights reserved.