在shell脚本中仅在一小时后提取数据

时间:2017-06-19 06:45:01

标签: linux unix awk grep logfiles

我有一个巨大的日志文件,其中包含每分钟变化的时间戳,格式如下:

2017-06-16 00:00:22 - Meter_1_L12_15_3_0 state updated to 124.035
2017-06-16 00:01:54 - Meter_1_L12_15_3_0 state updated to 124.041
2017-06-16 00:02:22 - Meter_1_L12_15_3_0 state updated to 124.047
2017-06-16 00:04:09 - Meter_1_L12_15_3_0 state updated to 124.053

我希望在一小时之后使用以下格式的shell脚本来提取日志数据:

2017-06-16 00:00:22 - Meter_1_L12_15_3_0 state updated to 124.035
2017-06-16 00:59:51 - Meter_1_L12_15_3_0 state updated to 124.391
2017-06-16 01:00:22 - Meter_1_L12_15_3_0 state updated to 124.396
2017-06-16 01:58:22 - Meter_1_L12_15_3_0 state updated to 124.718

请帮我完成这项任务。谢谢

编辑: Reevanshi评论了以下解释:
我想提取每小时的每个第一个和最后一个条目,比如任何时间,例如凌晨2:00到凌晨3:00,它们之间有100个条目,然后我只想要在该时间戳之间的第一个和最后一个条目。 / p>

2 个答案:

答案 0 :(得分:0)

您的输入和输出数据并不相互对应,但基本上,我认为您希望在小时更改时输出上一行和当前行。

因此,如果我将输入字段分隔符设置为" space"或冒号,我可以在第2个字段($2)中获取小时,这样就可以了:

awk -F'[ :]' '{if($2!=hr){hr=$2;print prev;print}} {prev=$0}' YourLogFile

答案 1 :(得分:0)

当我将部件调到head的第一个冒号时,我需要的不仅仅是简单的

awk -F: '{if (head!=$1) {if (str) print str; print;}
          head=$1;
          str=$0}' input.logfile

这在大多数情况下都有效,但如果在过去一小时内只有多行,则会失败。在这种情况下,你想要最后一行。在打印完最后一行时,你不应该打印它,所以你需要记住它。

awk -F: '{if (head!=$1) {if (str) print str; print $0;}
          prevhead=head;
          head=$1;
          str=$0};
       END {  if (head==prevhead) print str}' input.logfile