2016-07-05 38 views
0

我需要解析一个日志文件,以便下面的条目是这样的:打印最后一次出现在文件

Jul 23 17:38:06 192.168.1.100 638 "this message will always be the same" 
Jul 23 17:56:11 192.168.1.100 648 "this message will always be the same." 


Jul 23 18:14:17 192.168.1.101 "this message will always be the same." 
Jul 23 18:58:17 192.168.1.101 "this message will always be the same." 

是这样的:

Jul 23 17:56:11 192.168.1.100 648 "this message will always be the same." 
Jul 23 18:58:17 192.168.1.101 "this message will always be the same." 

基本上我我正在做的是获取具有重复IP地址但具有不同时间戳的文件,并查找每个IP地址的最后一次(或最近一次),并将其打印到屏幕或将其导入另一个文件。

我曾尝试:

我写,我认为会允许我这样做一个bash脚本,但它无法正常工作。

#!/bin/bash 

/bin/grep 'common pattern to all lines' /var/log/file | awk '{print $4}' | sort - u > /home/user/iplist 

while IFS='' read -r line || [[ -n "$line" ]]; do 
echo "$line" 
done < "/home/user/iplist" 

awk '/'$line'/ {a=$0}END{print a} ' /var/log/logfile 

该脚本运行并输出每个IP地址,但不会打印除最后一个之外的全部行。

恩..

192.168.100.101 
192.168.100.102 
192.168.100.103 
Jul 23 20:20:55 192.168.100.104 "this message will always be the same." 

在脚本中的第一个命令需要一个IP的所有独特的事件,并发送到文件中。 while循环为每行分配一个“$ line”变量,然后将其传递给awk,我认为这将使用每个IP,然后搜索实际文件并打印每个文件的最后一个出现。我怎样才能使这个工作,无论是与脚本或awk一班?

+0

“每个IP地址找到最后一次出现(或时间最近的)” - 所以你需要的最后一个实例,或者你最需要最近的时间?或者它们是一样的,因为它们是按时间排序的? – user31264

+0

另外,你是否需要以某种特定的顺序打印它们,或者顺序是任意的? – user31264

+0

他们应该是一个一样的 - 最后一次发生/最后一次看到。订单是任意的。 – user53029

回答

3
$ tac file | awk '!seen[$4]++' | tac 
Jul 23 17:56:11 192.168.1.100 648 "this message will always be the same." 
Jul 23 18:58:17 192.168.1.101 "this message will always be the same." 
1

您可以使用此awk命令:

awk 'NF{a[$4]=$0} NF && !seen[$4]++{ips[++numIps]=$4} END { 
    for (i=1;i<=numIps;i++) print a[ips[i]] }' file 

Jul 23 17:56:11 192.168.1.100 648 "this message will always be the same." 
Jul 23 18:58:17 192.168.1.101 "this message will always be the same." 
+1

是的好点,把它移到'END'块。 – anubhava

+1

又好点了。这也会使它在非gnu awk上工作。 – anubhava