簡體   English   中英

sed匹配日期和奇數格式

[英]sed matching dates & odd formats

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來解決此問題

提前致謝

盡管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)
}

很抱歉,冗長且不雅致的解決方案。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM