根据Unix时间戳过滤Linux日志 [英] Filter Linux logs based on Unix Timestamp

查看:70
本文介绍了根据Unix时间戳过滤Linux日志的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Linux服务器上有一个日志.条目的格式为:

I have a log on a linux server. The entries are in the format:

[时间戳(自1970年1月1日以来的秒数)]日志数据输入

[timestamp (seconds since jan 1 1970)] log data entry

我需要一个bash脚本,该脚本将使用日志文件的名称并仅输出昨天的条目(从前一天的12:00到23:59:59)并将这些行输出到新文件.

I need a bash script that will take the name of the log file and output only yesterdays entries (from 12:00 to 23:59:59 of previous day) and output those lines to a new file.

我见过各种脚本可以根据日期过滤日志,但是到目前为止,所有这些脚本都以更具人类可读性的格式处理日期戳,或者不是动态的.他们依靠硬编码的日期.我想要一个脚本,它将每天在cron作业中运行,因此它必须知道每次运行时的当前日期.

I've seen various scripts that filter logs based on dates but all of them so far deal with date stamps in more human readable formats, or are not dynamic. They rely on hard coded dates. I want a script that is going to run in a cron job daily so it has to be aware of what the current date is each time it runs.

谢谢.

更新:这是我到目前为止的内容.似乎从来没有对日期进行过评估.它为日期打印00,以便一切顺利.

Update: This is what I have so far. It just never seems to do the evaluation of the date. It prints 00 for the date so everything gets through.

head -5 logfile.log | awk '{
    if($1 >= (date -d "today 00:00:00" +"%s")) 
        print $1 (date -d "today 00:00:00" +"%s");
    }' 

我很困惑,即使日期计算正确,$ 1的方括号内也会有数字,而我的日期就是数字.如果字符串的格式不同,是否可以正确进行比较?我还没有弄清楚如何将date返回的日期数字推入带括号的字符串中.

I'm confused though, even if the date evaluates properly, $1 is going to have numbers inside square brackets, and my date will be just numbers. Will it do the comparison properly if the strings are formatted differently like that? I haven't figured out how to shove the date number returned by date into a string with brackets yet.

推荐答案

好吧,也许使用Dale所说的日期.但是,使用一些技巧来提取"["和]",然后比较日期.像这样:

Well, maybe using the dates as Dale said. But using a little trick to extract the "[" and "]", and after compare the dates. Something like this:

YESTERDAY=$(date -d "yesterday 00:00:00" +"%s")
TODAY=$(date -d "today 00:00:00" +"%s")

# Combine the processing in awk
awk -v MIN=${YESTERDAY} -v MAX=${TODAY} -F["]""["] '{  if ( $2 >=  MIN && $2 <= MAX) print $0}' logfile.log

这篇关于根据Unix时间戳过滤Linux日志的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆