sort logfile by timestamp on linux command line

前端 未结 7 1904
自闭症患者
自闭症患者 2020-12-11 01:34

I have a logfile with entries like:

...    
freeswitch.log:2011-09-08 12:21:07.282236 [ERR] ftdm_queue.c:136 Failed to enqueue obj 0x7f2cda3525c0 in queue 0x         


        
相关标签:
7条回答
  • 2020-12-11 02:01

    Crude but effective technique: Prefix each line with a numeric representation of the date, sort numerically, then remove the extra info.

    Oneliner:

    while IFS=' ' read -r name_date trailing ; do date=$(cut -d: -f2 <<<"$name_date") ; printf '%s:%s\n' $(date -d "$date" +%s) "$name_date $trailing" ; done < freeswitch.log | sort -k1 -t: | cut -d: -f2-
    

    Shell script:

    #!/usr/bin/env bash
    
    logfile="$1"
    
    if [ -f "$logfile" ] ; then
        while IFS=' ' read -r name_date trailing ; do
                date=$(cut -d: -f2 <<<"$name_date")
            printf '%s:%s\n' $(date -d "$date" +%s) "$name_date $trailing"
        done < "$logfile" | sort -k1 -t: | cut -d: -f2-
    fi
    

    Note: Requires GNU date.

    If the output at this point is the reverse of what you want it is simple to pipe through tac or to modify the script to also pass -r to sort.

    EDIT: I missed the part where the filename was literally on each line. Updated version will now actually work.

    0 讨论(0)
提交回复
热议问题