计算以日期和时间戳开头的行数

计算以日期和时间戳开头的行数

我如何计算以距现在一小时或更短时间匹配的日期和时间戳开头的行数?

此位置的文件/home/liamcomfort/my.log

日志格式的示例如下:

Nov 10 04:03:00 Friendly. Wholesale sweaters, no problems, sometimes overnight, inexpensive than large element. 
Nov 10 04:03:07 Now want to grab the spotlight form the official website. 
Nov 10 04:04:01 No matter who, overall planning, implementation than electric. I will be traveling to Japan tomorrow, at best. 
Nov 10 04:04:01 Get's not, the element of which that can be used, unless the slough, the bow to the policies, comprehensive package

答案1

now=$( date +%s )
one_hour_ago=$( date -d "now - 1 hour" +%s )
count=0
while read -ra words; do
    timestamp=$( date -d "${words[@]:0:3}" +%s )
    if (( $one_hour_ago <= $timestamp && $timestamp <= $now )); then
        (( count ++ ))
    fi
done < filename
echo $count

答案2

while read M D T R; do [[ $(( $( date +"%s" ) - $( date -d "$M $D $T" +"%s" ) )) -lt 3600 ]] && (( ++C )); done; echo $C

很棒的一行代码(抱歉,无法抗拒),虽然有用,但是非常非常丑陋...
但是,下面的代码可以优雅地完成它:

#!/bin/bash

#read the current date/time in unixtime format
NOW=$( date +"%s" )

while read MONTH DAY TIME REST
do
    #change the read date/time to unixtime
    THEN=$( date -d "$MONTH $DAY $TIME" +"%s" )

    #if the difference is less than 1 hour (=3600 seconds), increase the count
    (( ( NOW - THEN ) < 3600 )) && (( ++COUNT ))

done <"/home/liamcomfort/my.log"

echo "$COUNT"

相关内容