using awk to check between two dates

前端 未结 2 1588
刺人心
刺人心 2020-12-21 11:48

I have a file with multiple data structures in it like so:

eventTimestamp: 2010-03-23T07:56:19.166
result: Allowed
protocol: SMS
payload: RCOMM_SMS

eventTim         


        
相关标签:
2条回答
  • 2020-12-21 12:14

    The key observation is that you can compare your timestamps using alphanumeric comparisons and get the correct answer - that is the beauty of ISO 8601 notation.

    Thus, adapting your code slightly - and formatting to avoid scroll bars:

    awk 'BEGIN {
            FS  = "\n"
            RS  = ""
            OFS = ";"
            ORS = "\n"
            t1  = "2010-03-23T07:45:00"
            t2  = "2010-03-23T08:00:00"
            m1  = "eventTimestamp: " t1
            m2  = "eventTimestamp: " t2
            }
    $1 ~ /eventTimestamp:/ && $4 ~ /SMS-MO-FSM(-INFO)?$/ {
        if ($1 >= m1 && $1 <= m2) print $1, $2, $3, $4;
    }' "$@"
    

    Obviously, you could put this into a script file - you wouldn't want to type it often. And getting the date range entered accurately and conveniently is one of the hard parts. Note that I've adjusted the time range to match the data.

    When run on the sample data, it outputs one record:

    eventTimestamp: 2010-03-23T07:56:19.186;result: Allowed;protocol: SMS;payload: SMS-MO-FSM
    
    0 讨论(0)
  • 2020-12-21 12:29

    A bit of a kludge, but this script assumes you have the unix "date" command. Also hard coded your start and end timestamps in the BEGIN block. Note that your test data listed above does not fall within your sample start/end times.

    #!/usr/bin/awk -f
    BEGIN {
            command="date -f\"%s\" -d \"2010-03-23 12:56:47\""; command | getline startTime; close(command)
            command="date -f\"%s\" -d \"2010-03-23 13:56:47\""; command | getline endTime; close(command)
    }
    
    $0 ~ /^eventTimestamp:/ {
            command="date -f\"%s\" -d " $2; command | getline currTime; close(command)
    
            if (currTime >= startTime && currTime <= endTime) {
                    printIt="true"
            }else{
                    printIt="false";
            }
    }
    
    printIt == "true" { print }             
    
    0 讨论(0)
提交回复
热议问题