gpt4 book ai didi

用于从两个日期范围之间的日志文件中提取数据的 Perl 脚本,文件中不需要输入日期

转载 作者:行者123 更新时间:2023-12-02 04:35:51 25 4
gpt4 key购买 nike

我有一个日志文件,每一行都有一个时间戳,如下所示。我需要获取两个日期之间的数据。例如,获取 8 月 9 日 16:24:23 和 8 月 9 日 16:28:00 之间的数据,即使它们不在文件中。

Aug  9 16:24:21 linux-447z dbus-daemon[685]: 
Aug 9 16:24:21 linux-447z dbus[685]: [system] Activating service
Aug 9 16:24:21 linux-447z dbus-daemon[685]:
Aug 9 16:24:21 linux-447z dbus-daemon[685]: dbus[685]: [system]
Aug 9 16:24:21 linux-447z dbus[685]: [system] Successfully activated
Aug 9 16:27:46 linux-447z dhcpcd[3422]: eth0: renewing lease of 192.168.37.128
Aug 9 16:27:46 linux-447z dhcpcd[3422]: eth0: leased 192.168.37.128 for 1800 seconds
Aug 9 16:27:46 linux-447z dhcpcd[3422]: eth0: adding IP address 192.168.37.128/24
Aug 9 16:27:46 linux-447z dhcpcd[3422]: eth0: adding
Aug 9 16:27:47 linux-447z dhcpcd[3422]: eth0: Failed to lookup
Aug 9 16:27:47 linux-447z ifup: eth0
Aug 9 16:27:48 linux-447z SuSEfirewall2:
Aug 9 16:29:03 linux-447z dbus[685]: [system] Activating service

最佳答案

您可以使用 Time::Piece (自 Perl 5.10 以来的核心模块)进行日期解析和比较:

#!/usr/bin/perl

use strict;
use warnings;
use 5.010;

use Time::Piece;

my $format = '%b %e %T';
my $start = Time::Piece->strptime('Aug 9 16:24:23', $format);
my $end = Time::Piece->strptime('Aug 9 16:28:00', $format);

while (<DATA>) {
my ($timestamp) = /(^\w+\s+\d+\s+\d\d:\d\d:\d\d)/;
my $t = Time::Piece->strptime($timestamp, $format);

print if $t >= $start && $t <= $end;
}

__DATA__
Aug 9 16:24:21 linux-447z dbus-daemon[685]:
Aug 9 16:24:21 linux-447z dbus[685]: [system] Activating service
Aug 9 16:24:21 linux-447z dbus-daemon[685]:
Aug 9 16:24:21 linux-447z dbus-daemon[685]: dbus[685]: [system]
Aug 9 16:24:21 linux-447z dbus[685]: [system] Successfully activated
Aug 9 16:27:46 linux-447z dhcpcd[3422]: eth0: renewing lease of 192.168.37.128
Aug 9 16:27:46 linux-447z dhcpcd[3422]: eth0: leased 192.168.37.128 for 1800 seconds
Aug 9 16:27:46 linux-447z dhcpcd[3422]: eth0: adding IP address 192.168.37.128/24
Aug 9 16:27:46 linux-447z dhcpcd[3422]: eth0: adding
Aug 9 16:27:47 linux-447z dhcpcd[3422]: eth0: Failed to lookup
Aug 9 16:27:47 linux-447z ifup: eth0
Aug 9 16:27:48 linux-447z SuSEfirewall2:
Aug 9 16:29:03 linux-447z dbus[685]: [system] Activating service

输出:

Aug  9 16:27:46 linux-447z dhcpcd[3422]: eth0: renewing lease of 192.168.37.128
Aug 9 16:27:46 linux-447z dhcpcd[3422]: eth0: leased 192.168.37.128 for 1800 seconds
Aug 9 16:27:46 linux-447z dhcpcd[3422]: eth0: adding IP address 192.168.37.128/24
Aug 9 16:27:46 linux-447z dhcpcd[3422]: eth0: adding
Aug 9 16:27:47 linux-447z dhcpcd[3422]: eth0: Failed to lookup
Aug 9 16:27:47 linux-447z ifup: eth0
Aug 9 16:27:48 linux-447z SuSEfirewall2:

关于用于从两个日期范围之间的日志文件中提取数据的 Perl 脚本,文件中不需要输入日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21995141/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com