![如何按時間複製access.log行?](https://rvso.com/image/52087/%E5%A6%82%E4%BD%95%E6%8C%89%E6%99%82%E9%96%93%E8%A4%87%E8%A3%BDaccess.log%E8%A1%8C%EF%BC%9F.png)
我在 CentOS 中有一個巨大的網頁伺服器 access.log。我透過遠端 VPN 存取它,因此無法複製檔案或直接讀取它。
我知道我想要複製的日誌中的具體時間,但它太早了,太容易將日誌的尾部複製到文字檔案中。這是一行日誌的樣子。
10.255.16.203 - - [26/Mar/2014:16:35:13 +0000]
所以我的問題是:如果我知道要查找的時間字串,如何複製非常大的日誌的特定部分?
答案1
該grep
命令旨在僅顯示給定文件的匹配行。透過使用-C
選項,不僅可以顯示匹配的行,還可以顯示其之前和之後的一些行。
因此,要在您想要的行之前和之後添加 3 行:
$ grep -C 3 "26/Mar/2014:16:35:13 +0000" access.log
-A
您也可以使用和選項更精確地調整匹配行之後和/或之前顯示的行數-B
。其實-C 3
是一樣的-A 3 -B 3
。
如果有多個符合行,則會grep
顯示符合行區塊之前和之後的 3 行。
例子:
$ grep -C 3 "25/Mar/2014:10:40:59 +0100" access.log
10.0.0.44 - httpuse [25/Mar/2014:09:41:17 +0100] "GET /dummy/BIGDummy_133644_1565_DL.xml.gz HTTP/1.1" 200 507 "-" "-"
10.0.0.43 - httpuse [25/Mar/2014:09:59:51 +0100] "GET /dummy/BIGDummy_133647_48267_DL.xml.gz HTTP/1.1" 200 1677 "-" "-"
10.0.0.44 - httpuse [25/Mar/2014:10:40:42 +0100] "GET /dummy/BIGDummy_133664_39603_DL.xml.gz HTTP/1.1" 200 1677 "-" "-"
10.0.0.40 - httpuse [25/Mar/2014:10:40:59 +0100] "GET /dummy/BIGDummy_133664_DL.xml.gz HTTP/1.1" 200 60142 "-" "-"
10.0.0.41 - httpuse [25/Mar/2014:10:40:59 +0100] "GET /dummy/BIGDummy_133667_23124_DL.xml.gz HTTP/1.1" 200 5202 "-" "-"
10.0.0.40 - httpuse [25/Mar/2014:10:43:09 +0100] "GET /dummy/BIGDummy_133668_46_DL.xml.gz HTTP/1.1" 200 445 "-" "-"
10.0.0.42 - httpuse [25/Mar/2014:10:43:10 +0100] "GET /dummy/BIGDummy_133668_4116_DL.xml.gz HTTP/1.1" 200 597 "-" "-"
10.0.0.40 - httpuse [25/Mar/2014:10:43:13 +0100] "GET /dummy/BIGDummy_133665_DL.xml.gz HTTP/1.1" 200 57902 "-" "-"
從man grep
:
NAME
grep, egrep, fgrep - print lines matching a pattern
SYNOPSIS
grep [options] PATTERN [FILE...]
DESCRIPTION
Grep searches the named input FILEs (or standard input if no files are named,
or the file name - is given) for lines containing a match to the given PATTERN.
By default, grep prints the matching lines.
OPTIONS
-A NUM, --after-context=NUM
Print NUM lines of trailing context after matching lines.
Places a line containing -- between contiguous groups of matches.
-B NUM, --before-context=NUM
Print NUM lines of leading context before matching lines.
Places a line containing -- between contiguous groups of matches.
-C NUM, --context=NUM
Print NUM lines of output context.
Places a line containing -- between contiguous groups of matches.