我正在处理一个日志文件,我想打印从特定日期到日志文件末尾的内容。例如,特定日期为 ($sd=27/Dec/2002)。现在我想搜索这一天,并从这一天开始打印到日志文件末尾!但如果 27/Dec 不在日志文件的项目中怎么办?它应该搜索项目 >= $sd (27/Dec),我该怎么做?
此代码仅搜索 $Sd ,即 27/Dec/2002 ,我想搜索项目> = $sd
sed -n "$(awk '/'$sd'/ {print NR}' serverlog.log.log | head -1),$ p" serveerlog.log|cut -d: -f1
解决了 !
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}' ll.log|cut -d: -$
答案1
如果您需要打印某个日期第一次出现后的行,请尝试以下操作:
tail --lines=\+`cat your_file | grep -n "27/Dec/2002" | awk -F : '{ print $1 }'` your_file
答案2
#!/bin/bash
sd=27/Sep/2011
from=$(date -d "$(echo "$sd" | awk 'BEGIN { FS = "/"; } { print $1" "$2" "$3" 00:00:00" }')" +%s)
while read line
do
date=$(echo $line | awk '{ print substr($4, 2, length($4)-1) }' | awk 'BEGIN { FS = "[/:]"; } { print $1" "$2" "$3" "$4":"$5":"$6 }')
dateepoch=$(date -d "$date" +%s)
if [ $dateepoch -ge $from ]; then
line_number=$(grep -n $(echo $line | awk '{ print substr($4, 2, length($4)-1) }') -m 1 input | cut -d: -f1)
break
fi
done < input
awk 'NR >= '$line_number'' input
文件input
:
127.0.0.1 - - [18/Sep/2011:21:57:28 +0700] "GET /favicon.ico HTTP/1.1" 404 268
127.0.0.1 - - [19/Sep/2011:22:07:52 +0700] "GET /abcde.png HTTP/1.1" 404 277
127.0.0.1 - - [20/Sep/2011:22:07:54 +0700] "GET /abcde.png HTTP/1.1" 404 277
127.0.0.1 - - [21/Sep/2011:22:11:05 +0700] "GET /index HTTP/1.1" 502 462
127.0.0.1 - - [22/Sep/2011:22:31:22 +0700] "GET / HTTP/1.1" 502 462
127.0.0.1 - - [23/Sep/2011:10:17:34 +0700] "GET / HTTP/1.1" 502 471
127.0.0.1 - - [24/Sep/2011:10:17:36 +0700] "GET /favicon.ico HTTP/1.1" 404 277
127.0.0.1 - - [25/Sep/2011:10:17:36 +0700] "GET /favicon.ico HTTP/1.1" 404 277
127.0.0.1 - - [26/Sep/2011:11:10:33 +0700] "GET / HTTP/1.1" 502 469
127.0.0.1 - - [27/Sep/2011:11:10:34 +0700] "GET /favicon.ico HTTP/1.1" 404 275
127.0.0.1 - - [28/Sep/2011:11:10:34 +0700] "GET /favicon.ico HTTP/1.1" 404 275
结果:
$ ./date.sh
127.0.0.1 - - [27/Sep/2011:11:10:34 +0700] "GET /favicon.ico HTTP/1.1" 404 275
127.0.0.1 - - [28/Sep/2011:11:10:34 +0700] "GET /favicon.ico HTTP/1.1" 404 275
如果更改sd
为17/Sep/2011
:
$ ./date.sh
127.0.0.1 - - [18/Sep/2011:21:57:28 +0700] "GET /favicon.ico HTTP/1.1" 404 268
127.0.0.1 - - [19/Sep/2011:22:07:52 +0700] "GET /abcde.png HTTP/1.1" 404 277
127.0.0.1 - - [20/Sep/2011:22:07:54 +0700] "GET /abcde.png HTTP/1.1" 404 277
127.0.0.1 - - [21/Sep/2011:22:11:05 +0700] "GET /index HTTP/1.1" 502 462
127.0.0.1 - - [22/Sep/2011:22:31:22 +0700] "GET / HTTP/1.1" 502 462
127.0.0.1 - - [23/Sep/2011:10:17:34 +0700] "GET / HTTP/1.1" 502 471
127.0.0.1 - - [24/Sep/2011:10:17:36 +0700] "GET /favicon.ico HTTP/1.1" 404 277
127.0.0.1 - - [25/Sep/2011:10:17:36 +0700] "GET /favicon.ico HTTP/1.1" 404 277
127.0.0.1 - - [26/Sep/2011:11:10:33 +0700] "GET / HTTP/1.1" 502 469
127.0.0.1 - - [27/Sep/2011:11:10:34 +0700] "GET /favicon.ico HTTP/1.1" 404 275
127.0.0.1 - - [28/Sep/2011:11:10:34 +0700] "GET /favicon.ico HTTP/1.1" 404 275