在日志文件中搜索并打印特定日期

时间:2011-09-28 15:20:08

标签: shell date logfile

我正在使用日志文件,我想从特定日期打印到结束。例如,该特定日期是($ sd = 27 / Dec / 2002)。现在我想搜索这一天并从它打印到日志文件结束!但是如果27 / Dec不在日志文件中的项目中呢?它应该搜索项目> = $ sd(27 / Dec),我怎么能这样做?

此代码只搜索$ Sd,即2002年12月27日,我想搜索商品> = $ sd

sed -n "$(awk '/'$sd'/ {print NR}' serverlog.log.log | head -1),$ p" serveerlog.log|cut -d: -f1

日志文件示例:

213.64.237.213 - - [23/Dec/2002:03:02:22 +0100]
213.132.36.66 - - [28/Dec/2002:19:33:29 +0100]

并且日志文件已排序!

1 个答案:

答案 0 :(得分:-1)

使用awk会非常容易。见下面的例子:

kent$  cat log.txt
213.64.237.213 - - [20/Dec/2002:03:02:22 +0100]
213.64.237.213 - - [20/Dec/2002:03:02:22 +0100]
213.64.237.213 - - [20/Dec/2002:03:02:22 +0100]
213.64.237.213 - - [20/Dec/2002:03:02:22 +0100]
213.64.237.213 - - [20/Dec/2002:03:02:22 +0100]
213.64.237.213 - - [23/Dec/2002:03:02:22 +0100]
213.64.237.213 - - [23/Dec/2002:03:02:22 +0100]
213.64.237.213 - - [23/Dec/2002:03:02:22 +0100]
213.64.237.213 - - [25/Dec/2002:03:02:22 +0100]
213.64.237.213 - - [25/Dec/2002:03:02:22 +0100]
213.64.237.213 - - [25/Dec/2002:03:02:22 +0100]
213.64.237.213 - - [25/Dec/2002:03:02:22 +0100]
213.132.36.66 - - [28/Dec/2002:19:33:29 +0100]

kent$  sd=21/Dec/2002




kent$  awk -F'[:[]' -v d=$sd '$2>d' log.txt

<强>输出

213.64.237.213 - - [23/Dec/2002:03:02:22 +0100]
213.64.237.213 - - [23/Dec/2002:03:02:22 +0100]
213.64.237.213 - - [23/Dec/2002:03:02:22 +0100]
213.64.237.213 - - [25/Dec/2002:03:02:22 +0100]
213.64.237.213 - - [25/Dec/2002:03:02:22 +0100]
213.64.237.213 - - [25/Dec/2002:03:02:22 +0100]
213.64.237.213 - - [25/Dec/2002:03:02:22 +0100]
213.132.36.66 - - [28/Dec/2002:19:33:29 +0100]

<强>更新

尝试这个awk行:$ sd是变量。希望它对你有用。

kent$  awk -F'[:[]' -v vd=$sd 'BEGIN{ gsub(/\//," ",vd);"date +%s -d \""vd"\""|getline d} {p=$0;  gsub(/\//," ",$2); "date +%s -d \""$2"\""|getline o;if(o>d) print p}' log.txt